Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Activating and deactivating game objects in unity

Tags:

c#

unity3d

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. My problem is with deactivating and reactivating the gui because it is a game object. 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)
like image 326
Jonah Starling Avatar asked Nov 10 '22 21:11

Jonah Starling


1 Answers

It seems that the code you've given here is in an Update. So the guiMenu object is being found and stored every frame.

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. 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);
        }
    }
like image 100
Venkat at Axiom Studios Avatar answered Nov 14 '22 22:11

Venkat at Axiom Studios