Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unity object reference not set to an instance of an object after SetActive false

I have a gameobject called Starting containing one Square and a legacy Text

enter image description here

The square serves as a button with the text saying "Press Start Button". The user will press the start button (mapped to spacebar). This will set the Starting gameObject to inactive. The code is as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
  if (CharacterController.started == false)
  {
      CharacterController.started = true;
      gameObject.SetActive(false);
  }
  else if (CharacterController.started == true)
  {
      CharacterController.started = false;
      gameObject.SetActive(true);
  }
}
}

CharacterController.started is a boolean for another gameObject.

I understand the GameObject.find() does not work if the gameObject has been set as inactive. I tried to find the GameObject from the CharacterController script like so:

void Update()
    {

        if (started)
        {
            if (Input.GetKeyDown(KeyCode.Space))
            {
                starting = GameObject.Find("Starting");
                starting.SetActive(true);
            }
        }
 }

This did not work and gives the error:

NullReferenceException: Object reference not set to an instance of an
object CharacterController.Update () (at
Assets/CharacterController.cs:33)

I am new to Unity. How do I get the Starting GameObject and set is as active?

>Solution :

You have basically answered your question, the GameObject "Starting" is inactive, so it will not find it.
Try referencing it at the start of your game on the CharacterController, like so:

public GameObject startingObject;
private void Start(){
startingObject = GameObject.Find("Starting"); //Find it here, or drag it into the hierarchy
}

then delete this line from the Update():

 starting = GameObject.Find("Starting");

since it is bad practice to use GameObject.Find() inside the Update method anyway.
It is also more preferable to reference Components to the hierarchy than using GameObject.Find(""), if possible of course, but both solutions should work fine

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading