ARFoundation - enable/disable component in the placed prefeb

Hi guys

I have some trees in my placed prefab, which I switch off with a button. The same button is also suppose to switch it back on (make active), but for the life of me I cant figure out how to get past the error: “Object reference not set to an instance of an object”

Gameobject myTrees;

    public void ShowHideTrees()
    {
        myTrees = GameObject.FindGameObjectWithTag("Trees");
        if (myTrees.active)
        {
            myTrees.SetActive(false);
        }
        else
        {
            myTrees.SetActive(true);
        }


    }

The trees are switched off fine with the button, but when I want to switch them back on, I get the dreaded “Object reference not set to an instance of an object” issue. I can’t make the GameObject public and assign it in the Inspector since the prefab is only placed after the app runs.

Is this the right subforum for such questions? Let’s keep this forum AR related.
There are other subforums for beginner scripting.

But it is always good to start with the documentation before you write a post, take note of the word “active”:

activeSelf or activeinHierarchy yields the same results so I’m afraid that’s no help at all.

Again, the object is clearly there, and in the scene at the time I run the code. What I dont understand is, why can I find it with it’s tag, then switch it off, but immediately after that, I can’t find it using same tag and switch it back on

See https://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html . FindGameObjectWithTag only searches active GameObjects, so after you disable your GameObject, the next call to FindGameObjectWithTag will return null, which explains the exception you mentioned.

1 Like

Ah that makes perfect sense now. Thanks @tdmowrer and @Saicopate