所以下面你会找到一小段代码。这段代码的作用是允许玩家点击'p'键暂停游戏,当发生这种情况时,会弹出一个gui,玩家看起来和动作控制被禁用。我的问题是停用和重新激活gui,因为它是一个游戏对象。它让我停用它,但是当我尝试激活它时,我收到错误。
代码:
UnityEngine.Component walkScriptOld = GameObject.FindWithTag ("Player").GetComponent ("CharacterMotor");
UnityEngine.Behaviour walkScript = (UnityEngine.Behaviour)walkScriptOld;
UnityEngine.GameObject guiMenu = GameObject.FindWithTag ("Canvas");
if ((Input.GetKey ("p")) && (stoppedMovement == true)) {
stoppedMovement = false;
walkScript.enabled = true;
guiMenu.SetActive(true);
} else if ((Input.GetKey ("p")) && (stoppedMovement == false)) {
stoppedMovement = true;
walkScript.enabled = false;
guiMenu.SetActive(false);
}
错误:
NullReferenceException: Object reference not set to an instance of an object MouseLook.Update () (at Assets/Standard Assets/Character Controllers/Sources/Scripts/MouseLook.cs:44)
答案 0 :(得分:1)
您在此处提供的代码似乎在更新中。因此,每个帧都会找到并存储guiMenu对象。
您要做的是将对象缓存在Awake或Start函数中,其余代码将正常工作。另请注意,缓存始终是一种很好的做法。
//This is the Awake () function, part of the Monobehaviour class
//You can put this in Start () also
UnityEngine.GameObject guiMenu;
void Awake () {
guiMenu = GameObject.FindWithTag ("Canvas");
}
// Same as your code
void Update () {
if ((Input.GetKey ("p")) && (stoppedMovement == true)) {
stoppedMovement = false;
walkScript.enabled = true;
guiMenu.SetActive(true);
} else if ((Input.GetKey ("p")) && (stoppedMovement == false)) {
stoppedMovement = true;
walkScript.enabled = false;
guiMenu.SetActive(false);
}
}