On Button Click Enable - Disable GameObject Through Inspector

Through inspector on button click, how to enable and disable gameobject?

I have done this to enable and disable gameobject on button click but it is not working.

This can only be able to enable the gameobject but it can’t able to disable it. So how can I achieve this?

Code for CustomToggle script:

public class CustomToggle : MonoBehaviour
{
    bool isOn;
    //
    [SerializeField] GameObject onStateObj;
    [SerializeField] GameObject offStateObj;

    private void OnEnable()
    {
        isOn = false;
        onStateObj.SetActive(false);
        offStateObj.SetActive(true);
    }

    public void OnToggleButtonClick()
    {
        if (isOn)
        {
            // make this off
            isOn = false;
            onStateObj.SetActive(false);
            offStateObj.SetActive(true);
        }
        else
        {
            // make this on
            isOn = true;
            onStateObj.SetActive(true);
            offStateObj.SetActive(false);
        }
    }
}

bool isOn;

[SerializeField] GameObject onStateObj, offStateObj;

public void OnToggleButtonClick()
{
  isOn = !isOn;
  if (isOn)
  {
    onStateObj.SetActive(false);
    offStateObj.SetActive(true);
  }
  else
  {
    onStateObj.SetActive(true);
    offStateObj.SetActive(false);
  }
}

Then remove your GameObject.SetActive on your button click and use only the OnToggleButtonClick and you should be good to go.

@siddharth3322 ,Maybe 2 years to late, but for anyone googling this.

  • Use jimmiewalker suggestion if you want 1 button to toggle. Requires some scripting
  • You can also use 2 buttons, destroy and create for example. If you uncheck the box at gameobject.setActive, it removes the object, than on your other button, you check the box.