- Home /
Why setting an active object to false returns error of 'Object reference not set to an instance of an object'
void Update ()
{
if (Open == true)
{
GameObject.FindGameObjectWithTag("extra").SetActive(false);
Open_Door();
}
if (Close == true)
{
GameObject.FindGameObjectWithTag("extra").SetActive(true);
Close_Door ();
}
}
void OnTriggerEnter(Collider other)
{
if (other.tag=="Player")
{
Open=true;
Close = false;
}
}
void OnTriggerExit(Collider other)
{
if (other.tag=="Player")
{
Close = true;
Open=false;
}
}
The object with tag "extra" is needed to be set active/inactive according to Player's position. I have used Sphere Collider for this purpose. When the Player enters this Trigger followiung things happen
'extra' becomes inactive
"Object reference not set to an instance of an object" error is returned.
When the Player leaves the Trigger, the 'extra' does not become active again.
Kindly help me with this.
Answer by supernat · Apr 04, 2015 at 01:40 PM
The FindGameObjectWithTag() method only returns active objects in the scene. This is why you can't leave game objects inactive in the scene on startup if you want to find them in this way. There are 2 solutions.
Solution 1) Use a public GameObject variable, and assign the "extra" object in the Inspector. This may not be possible obviously if you're creating the "extra" game object at runtime or if you have a ton of scripts that need to reference it.
Solution 2) Use a private GameObject variable that you assign in the Start() method in the script above. Simply assign the game object variable using the FindGameObjectWithTag() method in Start(), then use that variable in the Update method. Note, you should be doing that anyway. FindGameObjectWithTag is expensive and should not be called in Update if you can help it.
Your answer
![](https://koobas.hobune.stream/wayback/20220613192126im_/https://answers.unity.com/themes/thub/images/avi.jpg)