I’m struggling to turn GameObjects off and on with a keypress. Unity shows an example with a light that can be toggled so I’ve attempted to convert their code… not working. Am I completely up the wrong tree…? Any help…?

using UnityEngine;
using System.Collections;

public class EnableComponent2 : MonoBehaviour
{
    private Cube myCube;


    void Start()
    {
        myCube = GetComponent<Cube>();
    }


    void Update()
    {
        if (Input.GetKeyUp(KeyCode.F1))
        {
            myCube.enabled = !myCube.enabled;
        }
    }
}

This is enabling/disabling the Cube component, I don’t recommend doing this. You should use GameObject.SetActive instead. The switch script should be on a different object than the object you are turning on and off.

Turning on and off a GameObject is different from toggling a component.

If you want to toggle on and off an entire GameObject (not one of its component), attach the following script to an empty gameObject, not the gameObject to toggle

 using UnityEngine;
 using System.Collections;

  // Rename the file to GameObjectToggle.cs
 public class GameObjectToggle : MonoBehaviour
 {
     public GameObject GameObjectToToggle; // Drag & drop the gameObject to toggle in the inspector
     public KeyCode ToggleKeyCode = KeyCode.F1; // Change the keycode to use in order to toggle

 
     void Update()
     {
         if (GameObjectToToggle != null && Input.GetKeyUp(ToggleKeyCode))
         {
             GameObjectToToggle.SetActive( !GameObjectToToggle.activeSelf ) ;
         }
     }
 }