- Home /
How to enable/disable UI buttons?
Basically, I want to disable a button, so when something happens, the button gets enabled and you can use it. I'm trying to make a more complex Roll-a-Ball game, so when you get all the Pickups, a button shows up and when you click it, it takes you to the next level. I have the button on the screen, and I wrote this code in the PlayerController script:
public Button myButton;
void start ()
{
myButton.interactable = false;
}
(obviously, I deleted the part that isn't about the button) Then, at the part with the "Win text":
void SetCountText ()
{
countText.text = "Collected pickups " + count.ToString () + "/" + maxCount;
if (count >= maxCount) {
winText.text = "Level conquered!";
myButton.interactable = true;
}
When I play the game, the button is there (I want it to be there from the beginning, just non-interactable) and I can't click it. After I collect all the Pickups and the "Level conquered!" text appears, the button is still non-interactable. How do I do it? Is there any more efficient way of doing it?
Answer by applemaniac · Jun 08, 2015 at 09:03 AM
You can change the interactable status via scripting, writing button.interactable = true for exemple. You can also make your button disappear by handling it like a gameobject, and gameobject.SetActive(true) when oyu need it.
Answer by Nosada · May 11, 2017 at 02:05 PM
myButton.interactable = false; this works to get rid of the button, but the text (a child of the button) is still showing. I also tried myButton.enable= false;
For now I guess I'll just delete the text and include it as part of my image, unless someone posts a solution.
Answer by mafanbong8819 · Feb 14, 2017 at 09:00 AM
I try two days. Finally, I change the style, why not we just make the button onclick function empty? So the button will disable. Then the button image also can change, all condition can put under if the button will disable.
Here, I shared the video. It is my idea, hope this video is helpful. video- disable button
here is the function to disable the button, the whole script is displaying at the end of my video.
counter++;
if (counter % 2 == 0) {
mybutton.image.overrideSprite = blockA;
//condition for working button.
} else {
mybutton.image.overrideSprite = blockA_disable;
//condition for disable button
}
Answer by douglasdaquino · Apr 10, 2019 at 06:05 PM
To make your text only appear when certain conditions are met, you can create a variable to store the text, and then use SetActive to false from the beginning, and then to true when needed, like:
public Text myText;
void Start(){
myText.SetActive(false);
}
void Update(){
if (conditions){
myText.SetActive(true);
}
}
Don't forget to assign the object in the inspector.