我主要遵循Unity的Udemy课程,其中第一个游戏完全基于控制台,程序试图猜测你想到的数字。我的第一个问题是,当使用Random.Range时,它将以随机数开始,但按向上箭头将首先将其恢复为较低的数字,然后在下次按下时增加它。下一个问题是按下向下箭头将始终将数字设置为1,之后不会增加。
using UnityEngine;
using System.Collections;
public class NumberWizard : MonoBehaviour {
int min = 1;
int max = 1000;
int randomGuess;
// Use this for initialization
void Start () {
int randomGuess = Random.Range (min, max);
print ("Welcome to Number Wizard!");
print ("Pick a number between " + min + " and " + max + ".");
print ("Is the number higher or lower than " + randomGuess + "?");
print ("Press up for higher, down for lower, and return for equals.");
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.UpArrow)) {
print ("Up arrow pressed");
min = randomGuess;
randomGuess = Random.Range (min, max);
print ("Higher or lower than " + randomGuess + "?");
}
if (Input.GetKeyDown (KeyCode.DownArrow)) {
print ("Down arrow pressed");
max = randomGuess;
randomGuess = Random.Range (min, max);
print ("Higher or lower than " + randomGuess + "?");
}
if (Input.GetKeyDown (KeyCode.Return)) {
print ("I win");
}
}
}
答案 0 :(得分:1)
在Start方法中,您将ranom编号分配给与类字段同名的局部变量:
int randomGuess = Random.Range (min, max);
这不会改变类字段值。即字段将保留默认值等于0.在更新部件中,您将此0指定给min或max字段。这就是你按下向下箭头后坚持的原因 - 所有进一步的random都是在范围(1,0)中生成的。您应该将随机数分配给类字段
randomGuess = Random.Range (min, max);