Jonah Starling
Jonah Starling

Reputation: 543

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. 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)

Upvotes: 6

Views: 6883

Answers (1)

Venkat at Axiom Studios
Venkat at Axiom Studios

Reputation: 2516

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

Upvotes: 1

Related Questions