Soviet peanut
Soviet peanut

Reputation: 13

Why does my script not find inactive GameObject when it should?

I have a script that should toggle active on my GameObject but when it disables it, it no longer finds the object.

Script:

GameObject cheet = GameObject.Find("base");

if (isOpen == true)
{
    cheet.SetActive(true);
}
else
{
    cheet.SetActive(false);
}

Upvotes: 1

Views: 99

Answers (1)

Mattias
Mattias

Reputation: 3907

GameObject.Find only returns active GameObjects, so I would recommend storing a reference to cheet in Start() or Awake(). As long as Cheet exists, this will ensure you have a reference and you only have to do it once.

using UnityEngine;

public class YourClass : MonoBehaviour
{
    private GameObject cheet;
    private bool isOpen; // Temp isOpen variable

    void Start()
    {
        // Store a reference to the GameObject
        cheet = GameObject.Find("base");
    }

    void Example1()
    {
        // set active based on varable isOpen
        cheet?.SetActive(isOpen);
    }

    void Example2()
    {
        // Could not find cheet (null)
        if(cheet == null)
            return;

        // set active based on varable isOpen
        cheet.SetActive(isOpen);
    }
}

Upvotes: 1

Related Questions