提问人:A Singh 提问时间:6/19/2023 最后编辑:WillemA Singh 更新时间:6/20/2023 访问量:60
变量保持静态
Variable Staying Static
问:
我在代码中遇到了变量问题。 没有像预期的那样增加。首先,我认为有什么东西迫使变量保持在零,但这是我们唯一使用 gems 变量的地方。gems
gems
...
private float gems = GameCtrl.instance.gems; //IN GAMECTRL SCRIPT: public float gems = 0.0f;
float gemsInc = 0.1f;
private void Start(){
...
StartCoroutine(IncrementGems());
}
...
IEnumerator IncrementGems() { //GOAL every 10 sec increment gems by 0.1
while (true)
{
yield return new WaitForSeconds(10);
gems += gemsInc;
Debug.Log(gems); // output: 0
gemAmount.text = "x" + gems; //output: "x0"
}
}
正如您在上面的代码中看到的,我已经尝试过调试。但是,调试的输出为 0。上述代码的目标是每 10 秒将该值增加 (0.1),但它不起作用。
任何帮助或想法将不胜感激。gems
gemsInc
[注意,表示有更多不相关的代码,并且不在实际脚本本身中]...
答:
0赞
Bluze Ocean
6/20/2023
#1
有时,错误可能会发生在代码的其他地方,而这些地方是你意想不到的。因此,代码中的错误可能发生在其他地方。 或者,可能是因为你有等待 10 秒的收益,而你没有等待 10 秒并认为它在玩游戏时不起作用?
无论如何,这是另一种无需协程即可完成的方法:
[SerializeField] private float gemsCount = 0f;
[SerializeField] private float gemsIncrement = 0.1f;
private float timer = 0f;
private const float timerMax = 10f; // every 10 seconds
private void Update()
{
timer += Time.deltaTime;
if (timer >= timerMax)
{
timer = 0f;
gemsCount += gemsIncrement;
Debug.Log("Gems: " + gemsCount);
}
}
像往常一样,您必须等待 10 秒才能看到第一个 gemCount 增加。
0赞
A Singh
6/20/2023
#2
好吧,我想我找到了一些东西。GameCtrl 对象实际上不在 Gem 所在的场景中。所以我相信,由于它无法访问 GameCtrl 对象,因此该变量无法正确递增
评论
0赞
Wyck
6/20/2023
#3
举个反例,我能够将此脚本添加到一个全新项目中的游戏对象中,并且它每秒正确输出一次递增的调试日志消息。
using System.Collections;
using UnityEngine;
public class NewBehaviourScript : MonoBehaviour
{
public float gems = 0.0f;
float gemsInc = 0.1f;
private void Start()
{
StartCoroutine(IncrementGems());
}
IEnumerator IncrementGems()
{
while (true) {
yield return new WaitForSeconds(1);
gems += gemsInc;
Debug.Log(gems);
}
}
}
2021.3.23.f1
您遇到的任何问题都可能与您发布的代码无关。
评论
0赞
A Singh
6/23/2023
感谢大家的帮助和建议!现在 gem 变量正在正确递增,没有任何问题。
下一个:在 C 循环中捕获的变量#
评论
Debug.Log
gemsInc
GameCtrl.instance.gems
gems