现在我正在尝试在Unity 4.6.9中构建一个数字向导游戏。到目前为止,除了第一次猜测外,一切都有效。
当游戏猜测数字为500时,你必须告诉它你的数字是高,低或等于500.理想情况下,如果你告诉它你的数字是高或低,它应该立即猜出一个新的数字(750表示较高,或250表示较低)。
问题在于它不会立即改变猜测。
当我告诉游戏该数字大于原始猜测时,Unity中的控制台说:
问题是第3行。它应该问“它是高于还是低于750?”,然后第4行应该询问“它是高于还是低于875?”,依此类推。
我真的不确定我在代码中做错了什么。如果有人愿意透视并指出我的错误,我将非常感激。
using UnityEngine;
using System.Collections;
public class NumberWizard : MonoBehaviour {
int max = 1000;
int min = 1;
int guess = 500;
// Use this for initialization
void Start () {
max += 1;
print ("Welcome to Number Wizard.");
print ("To begin, pick a number in your head, but don't tell me what it is.");
print ("The highest number you can pick is " +max +", and the lowest number you can pick is " +min +".");
print ("Is your number greater than " +guess +"?");
print ("Press Y if it is greater, N if it is lesser, or E if it is " +guess +".");
}
// Update is called once per frame
void Update () {
string NewGuess = "Is it higher or lower than " +guess +"?";
if (Input.GetKeyDown(KeyCode.Y)) {
min = guess;
guess = (max + min) / 2;
print (NewGuess);
} else if (Input.GetKeyDown(KeyCode.N)) {
max = guess;
guess = (max + min) / 2;
print (NewGuess);
} else if (Input.GetKeyDown(KeyCode.E)) {
print ("I won!");
}
}
}
再次,非常感谢任何帮助。
答案 0 :(得分:0)
问题是你永远不会更新你正在打印的NewGuess字符串,实际上包括新计算的猜测。试试这个:
void Update () {
string NewGuess = "Is it higher or lower than " +guess +"?";
if (Input.GetKeyDown(KeyCode.Y)) {
min = guess;
guess = (max + min) / 2;
NewGuess = "Is it higher or lower than " +guess +"?";
print (NewGuess);
} else if (Input.GetKeyDown(KeyCode.N)) {
max = guess;
guess = (max + min) / 2;
NewGuess = "Is it higher or lower than " +guess +"?";
print (NewGuess);
} else if (Input.GetKeyDown(KeyCode.E)) {
print ("I won!");
}
}
或者,更简洁的解决方案是创建一种新的打印方法,以便从您的Update方法调用,并将新猜测作为参数传递。
示例:
void PrintNewGuess(int newGuess)
{
String newGuessString = "Is it higher or lower than " +newGuess +"?";
print(newGuessString);
}