I have a GameObject BG, I want it to turn off when the Toggle changes.

private GameObject BG; // Use this for initialization void Start () { BG = GetComponent<GameObject>(); } // Update is called once per frame void Update () { } public void SetTheme(bool newValue) { BG.SetActive(!BG.activeSelf); } 

But this code does not work. Gives such an error:

MissingComponentException: There is no need for a game. You probably need to add a GameObject to the game object "BG". If your component needs to be checked before using it.

Although the project has Panel BG

  • Does this script hang on your BG site? - Andrey

1 answer 1

You are a little not so recorded something in BG. If the script hangs on BG, then there is no need to get the value of gameOjbject through GetComponent <> You just need to use gameObject instead

  BG = GetComponent<GameObject>(); 

Further everywhere you can use just gameObject and not BG. For example, It was

 BG.SetActive(!BG.activeSelf); 

It became

 gameObject.SetActive(!gameObject.activeSelf);