Search code examples
c#unity-game-enginebutton

Hide and show a button in Unity (C#)


I have a button (in UI), that I want to hide sometimes (but show again later), which means that it shouldn't show anymore and I shouldn't be able to click it. The only solution I found (that has actually managed to hide the button), is SetActive().

But in Update(), when I do SetActive(false) (the true/false is controlled with the variable wave_happening in my script), Update() doesn't run anymore, so I can't set it to true again. When I do GameObject.Find("Start Button").SetActive(true) in another script, it just gives me a NullReferenceException (Object reference not set to an instance of an object).

This is my Update() function:

void Update() {
    wave_happening = enemy_spawner_script.wave_happening;
    Debug.Log(wave_happening);
    transform.gameObject.SetActive(wave_happening);
}

Is there a solution to stop this problem, or another way to hide a button?

I'm fairly new to Unity and C#, so I don't know very much.


Solution

  • You can try disabling the button's rendering and functionality components:

    GetComponent<Button>().enabled = false; // remove functionality
    
    GetComponent<Image>().enabled = false; // remove rendering
    

    Now, adding that to your Update function, plus a few changes for performance so you are not enabling/disabling every single frame, only when needed:

    private bool isShowing = true; // or whatever your default value is
    
    void Update() {
        wave_happening = enemy_spawner_script.wave_happening;
        Debug.Log(wave_happening);
        
        if(wave_happening != isShowing) {
            show(wave_happening);
            isShowing = wave_happening;
        }
    }
    
    void show(bool isShow) {
        GetComponent<Button>().enabled = isShow; // remove functionality
    
        GetComponent<Image>().enabled = isShow; // remove rendering
    }