0
\$\begingroup\$

I am trying to find a gameobject, which is not active in the current scene.It throws Null Reference error.

GameObject gameObject;
void start(){
//a non active gameobject tagged with InactiveTag
gameObject = GameObject.FindGameObjectWithTag("InactiveTag"); 
}
void update(){
if(someCondition){
gameObject.setActive(true); //this line throws Null Reference error
}
}
\$\endgroup\$

3 Answers 3

1
\$\begingroup\$

You won't be able to find GameObjects that are inactive at start. you have 2 options:

  1. You can start with the object active, so the script can find and deactivate it, at start. But, then it has a reference to track.

  2. You can create a public var in your script and drag the object in question to the Inspector reference. Then your script will see it whether it active or not.

\$\endgroup\$
0
1
\$\begingroup\$

This is a method for getting a reference to an initially inactive object that avoids the overhead of the Find() type functions:

private GameObject myObject;

void Start()
{
    myObject = (GameObject)Instantiate(Resources.Load("MyObject"));
}

Your inactive objects must exist in a folder named "Resources" or within a sub-folder of it:

Assets> Resources

\$\endgroup\$
1
  • \$\begingroup\$ You can do this without Resources.Load by populating this script with a public GameObject prefab; reference to the prefab object to spawn, or with the new Addressables system. \$\endgroup\$
    – DMGregory
    Commented Apr 17, 2020 at 11:09
0
\$\begingroup\$

first set a trigger name to the game object

if(trigger.tag == "that game object") { gameObject.setActive(true); }

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .