gpt4 book ai didi

c# - 统一激活和停用游戏对象

转载 作者:太空狗 更新时间:2023-10-29 23:45:13 27 4
gpt4 key购买 nike

下面是一小段代码。这段代码的作用是允许玩家按下“p”键来暂停游戏,当发生这种情况时,会弹出一个图形用户界面,玩家的视线和移动控制将被禁用。我的问题是停用和重新激活 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)

最佳答案

您在此处提供的代码似乎在更新中。因此,每帧都会找到并存储 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);
}
}

关于c# - 统一激活和停用游戏对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27476993/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com