在Unity C#脚本中,我有一个单例游戏控制器对象,其中存储了游戏变量,但是在成员函数中访问它们时出现奇怪的行为。它打印初始化值,而不是当前值。但是,在更新功能中,它会每帧打印正确的值。我总结了下面的课程。控制器类具有对自身的静态引用。如果您需要了解其他详细信息,可以询问。我是C#和Unity的新手,所以我可能缺少一些明显的答案。
谢谢
public class controller : MonoBehaviour {
public int[] star = new int[64];
void Start(){ /* calls another function to set 0 for each star index */ }
void Update(){ // during gameplay star[0] gets a value of 1
print(star[0]); // prints correct value which is 1
}
public void checkValue(){
print(star[0]); // prints 0 incorrectly which should be 1
}
}
我已经建立了一个小例子。我创建了一个按钮和一个空的游戏对象GameController
。我将此代码添加到GameController
:
using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour {
public static GameController instance;
[System.NonSerialized] public int[] star = new int[64];
private void Awake()
{
if(instance == null)
instance = this;
else if(instance != this)
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
}
private void Start()
{
StartCoroutine(SetAllTo(1));
}
// for simulating some changes during the game
private IEnumerator SetAllTo(int value)
{
yield return new WaitForSeconds(2.0f);
for(int i = 0; i < star.Length; i++)
star[i] = value;
Debug.Log("Setting done");
}
public void PrintFirst()
{
Debug.Log(star[0]);
}
}
现在,我向OnClick
按钮添加了一个事件,将GameController
游戏对象拖到插槽中并选择了PrintFirst
。
我开始游戏,在“协程”日志之前单击一次,然后单击一次,控制台显示以下内容:
0
Setting Done
1
编辑:
该OnClick
事件的游戏对象必须在场景中,不能是Assets文件夹中的预制件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句