Toggle C# enabled state

I want to make a C# code turn on and off when you press the button “Inventory”. How would I do this?

Set up a variable of type Boolean. Have a toggle function that switches the boolean between true and false. Whenever your relevant code runs, you can have an if statement that checks first and only runs the code while the boolean is in a particular state.

1 Like

Hey,
Well this should work out for you.
Hope i was usefull!

using UnityEngine;

public class Inventory : MonoBehaviour {

    public bool IsActive = false;
    public KeyCode Inventory_K;
    public GameObject InventoryObject;
   
    void Update ()
    {
        if(Input.GetKeyDown(Inventory_K))
        {
            IsActive = !IsActive;               //if inventory is already True it will set it to false And the other way around.
        }                                       //all with the same key press that can be changed in the inspector.

        //-----------------------------------------------
        if (IsActive == true)
        {
            InventoryObject.SetActive(true);    //if the boolean is true
        }                                       //You can add her also more things like stopping the time With (Time.timeScale = 0;)
          else                                  //and turn it back with(Time.timeScale = 1;)
        {
            InventoryObject.SetActive(false);  //if the boolean is false
        }
    }
}
1 Like

No, I want to make a SCRIPT to turn on and off. enable and disable a different script itself

all scripts have a enabled property on them. So just get the object via GetComponent or via the inspector, and set its enabled field to false.

keep in mind disabling a script just stops its update method from running, you can still explicitly call methods on it.