Jon*_*ing 5 c# unity-game-engine
所以下面你会发现一小段代码.这段代码的作用是允许玩家点击'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);
}
Run Code Online (Sandbox Code Playgroud)
错误:
NullReferenceException: Object reference not set to an instance of an object MouseLook.Update () (at Assets/Standard Assets/Character Controllers/Sources/Scripts/MouseLook.cs:44)
Run Code Online (Sandbox Code Playgroud)
您在此处给出的代码似乎位于更新中。因此每帧都会找到并存储 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);
}
}
Run Code Online (Sandbox Code Playgroud)