【问题标题】:Unity can't access a random number from outside a functionUnity 无法从函数外部访问随机数
【发布时间】:2018-10-29 07:36:35
【问题描述】:

我想做一个数字猜谜游戏,让计算机猜你的数字,你也可以猜出它的数字,但在最后,我制作了一个随机数生成器,但遇到了一个问题。

我创建了名为onGuessEnter 的函数,当玩家在输入他的猜测后点击回车时调用它,我的问题是,如果我运行游戏(Visual Studio 不会对此产生问题)Unity 会因为包含以下行的错误:

RandomRangeInt 只能从主线程调用。

(如果我将随机生成器放入函数中,它会在每次输入命中时生成一个新的随机数)

有人可以帮助我使输入字段和随机生成器一起工作吗? (我的意思是它必须只生成一次随机数,而不是总是在按下 Enter 按钮时生成一个随机数,我可以从 onGuessEnter 访问该随机数)

using UnityEngine;
using System.Collections;
using UnityEngine.UI;


public class GuessManagerScript : MonoBehaviour {

public InputField input;
public Text text;
int random = Random.Range(0, 1000);

public void onGuessEnter() {

    print(random);
    int inum = int.Parse(input.text);

    if (inum == random) 
        text.text = "Congrats, you guessed it!";
    else if (inum < random)
        text.text = "Bigger!";
    else if (inum > random) 
        text.text = "Smaller!";
   }
}

【问题讨论】:

    标签: c# unity3d random int


    【解决方案1】:

    在这种情况下,您可以使用这样的简单技巧(见下文)。我们不能使用随机数生成器初始化random,但是我们可以将它设置为一个像-1这样的虚拟值,然后在我们的函数中我们可以检查它是否为-1,如果是,则生成一个随机数.这只会发生一次,因为随机数不能低于 0。

    int random = -1;
    
    public void onGuessEnter() {
        if(random == -1){
            random = Random.Range(0, 1000);
        }
        print(random);
        int inum = int.Parse(input.text);
    
        if (inum == random) 
            text.text = "Congrats, you guessed it!";
        else if (inum < random)
            text.text = "Bigger!";
        else if (inum > random) 
            text.text = "Smaller!";
       }
    }
    

    【讨论】:

      【解决方案2】:

      首先,您应该在Awake 中生成随机数,这样随机数只会创建一次,然后在您的onGuessEnter 方法中引用它。
      在此示例中,我查看用户是否按下了Return 键,然后我将调用您的方法来查看猜测是否正确。
      最后将整个脚本附加到gameObject,然后在编辑器中将InputFieldText 对象拖到GuessManagerScript 下提供的空槽中。

      public class GuessManagerScript : MonoBehaviour {
      int random; 
         void Awake(){
             random= Random.Range(0, 1000);
            }
          void Update() {
              if (Input.GetKeyDown(KeyCode.Return))
                  {
                      onGuessEnter();  
                   }
           }
      
      public void onGuessEnter() {
          int inum = int.Parse(input.text);
      
          if (inum == random) 
              text.text = "Congrats, you guessed it!";
          else if (inum < random)
              text.text = "Bigger!";
          else if (inum > random) 
              text.text = "Smaller!";
           }
         }
       }
      

      【讨论】:

      • @Kristóf 这个答案中的内容是您实际应该做的事情,即在Awake 函数中使用Random.Range 来初始化random 变量。您不需要调度程序或他的答案中使用的任何其他 API Pic
      猜你喜欢
      • 2021-11-06
      • 2021-01-11
      • 2011-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-25
      • 2013-02-23
      • 2013-01-18
      相关资源
      最近更新 更多