简体   繁体   English

统一激活和停用游戏对象

[英]Activating and deactivating game objects in unity

So below you will find a short snippet of code. 所以下面你会发现一小段代码。 What this code does is it allows the player to hit the 'p' key to pause the game and when this happens a gui pops up and the players look and movement controls are disabled. 这段代码的作用是允许玩家点击'p'键暂停游戏,当发生这种情况时,会弹出一个gui,玩家看起来和动作控制被禁用。 My problem is with deactivating and reactivating the gui because it is a game object. 我的问题是停用和重新激活gui,因为它是一个游戏对象。 It lets me deactivate it but when I try to activate it I get an error. 它让我停用它,但当我尝试激活它时,我收到一个错误。

Code: 码:

    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);
    }

Error: 错误:

NullReferenceException: Object reference not set to an instance of an object MouseLook.Update () (at Assets/Standard Assets/Character Controllers/Sources/Scripts/MouseLook.cs:44)

It seems that the code you've given here is in an Update. 看来你在这里给出的代码是在更新中。 So the guiMenu object is being found and stored every frame. 因此,每个帧都会找到并存储guiMenu对象。

What you want to do is cache the object in the Awake or Start function, and the rest of the code will work just fine. 你想要做的是将对象缓存在Awake或Start函数中,其余的代码将正常工作。 Also note that caching is always good practice. 另请注意,缓存始终是一种很好的做法。

    //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);
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM