Unity3D How To Set A UI Button Active

Unity3D How To Set A UI Button Active

When I design a game with a navigation menu or if I have button controls within the game UI, I often want to turn one off after a player action.

For example, the player clicks a button to fire a rocket. In this case, it is the last rocket thus, the rocket firing button should be disabled.

There are two methods to do this depending on if you want to totally remove/hide the button from the UI or just gray it out and disable it’s functionality.

Deactivate/Remove/Hide

To remove/hide the button, you would treat it as any GameObject and use the .SetActive method and set as false.

Using UnityEngine.UI;

public GameObject rocketButton;
void SomeFunction() {
     rocketButton.SetActive(false);
}

Reactivate/Display/Show

and to reactivate (for example if the player buys a new rocket) set the game object active to true:

Using UnityEngine.UI;

public GameObject rocketButton;
void SomeFunction() {
     rocketButton.SetActive(true);
}

Disable/Gray Out

If you don’t want to remove the UI control from the game area, you can just disable it from any function and slightly gray it out. Just reference the Button component of the game object UI element. Also don’t forget you need to include the namespace:

using UnityEngine.UI;
 
public GameObject myRocketButton;

void SomeFunction() {
     myRocketButton.GetComponent<Button>().interactable = false;
}

Unity3D UI Button Active

Re-Enable/Light Up

to re-enable the button just set it as true using the same code:

using UnityEngine.UI;
 
public GameObject myRocketButton;

void SomeFunction() {
     myRocketButton.GetComponent<Button>().interactable = true;
}

Unity3D UI Button Active

Unity3D How To Set A UI Button Active