Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

unity3d - 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.

question from:https://stackoverflow.com/questions/65601202/hide-and-show-a-button-in-unity-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...