Activation and deactivation of game objects in unity

So below you will find a short code snippet. What this code does is that it allows the player to press the p key to pause the game, and when that happens, gui appears and the players watch and the motion controls are disabled. My problem is to deactivate and restore gui because it is a game object. This allows me to deactivate it, but when I try to activate it, I get an error message.

the 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) 
+5
source share
1 answer

It seems that the code indicated here is in an update. Thus, the guiMenu object is found and saved 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 fine. Also note that caching is always a 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); } } 
+1
source

Source: https://habr.com/ru/post/1209045/


All Articles