【发布时间】:2016-07-15 00:58:23
【问题描述】:
我有一个带有网格布局的面板,我在其中放置了预制文本对象的实例化克隆。
可视计时器表示的每个实例都有一个附加的计时器脚本。
还有一个将这些文本对象添加到列表(面板)的按钮:
当我的按钮被按下时,我从新计时器中调用StartTimer 函数(我省略了所有用于实例化研究名称文本的类似代码):
public void AddResearch() {
...
float timeInSeconds = (float) Random.Range(5, 16);
...
GameObject newTimerObject = (GameObject) Instantiate(
researchTimerPrefab,
researchList.transform.position,
researchList.transform.rotation);
newTimerObject.transform.SetParent(researchList.transform);
...
newTimerObject.GetComponent<ResearchTimer> ().StartTimer (timeInSeconds);
...
}
在StartTimer(float) 所在的ResearchTimer 脚本类中,我遇到了我要查找的问题:
public class ResearchTimer : MonoBehaviour {
public float timeRemaining;
private Text visualText;
private bool isStarted; //This is the variable I don't understand
void Start () {
visualText = GetComponent<Text> ();
//I initiate it to false here because
//I don't want update called before the timer starts.
isStarted = false;
}
void Update () {
//Here, isStarted is always false after setting it to true "StartTimer"
if (!isStarted) return;
//code to update text representation of the timer
...
}
public void StartTimer(float timeInSeconds) {
timeRemaining = timeInSeconds;
isStarted = true;
//When I set a breakpoint here, the "isStarted" variable is changed to true,
//but the next time the Update function runs, it's false again.
//That is the part I don't understand
InvokeRepeating ("decreaseTimeRemaining", 1.0f, 1.0f);
}
void decreaseTimeRemaining()
{
//If I set isStarted here, it shows correctly (as per screenshot),
//but then it won't be set before the first second has passed
isStarted = true;
timeRemaining--;
}
...
}
isStarted 未在代码中的其他任何位置设置。为什么会这样?
顺便说一句,我知道我似乎不需要这个变量,但我仍然很好奇它为什么会发生。
【问题讨论】:
-
您知道 isStarted 默认以
false开头吗?你问的是这个吗? -
我真正要问的是为什么在调用
StartTimer()之后isStarted仍然是假的。我知道Start()在我调用StartTimer()之前就被调用了,所以我不明白为什么/如何在此之后再次将其设置为false。这有帮助吗? -
好点。这是我的错误,也是一个非常尴尬的错误。我一定很困惑。对不起。
-
这类问题很容易解决。确保您包含 >>>>所有
-
我不知道你为什么在这里向 cmets 发送垃圾邮件。我知道如何使用
Debug.Log()。正如您所指出的, isStarted 是一个私有变量,那么为什么其他文件很重要?这是every mention of isStarted,我已经在上面的问题中向您展示过。讨论++与+=1或v = v+1似乎都与讨论无关。请在别处讨论。