I have an upgrade menu with a buy button. I want to change what it does every time you click it. How should I best approach this?
Something like this. Add a Canvas to a scene and a button to the canvas. Create this script and add it to some gameobject in the scene (the Canvas will be fine). Drag the button you created into the slot in this script. The button will say “option 1”. When you click it, it will change to option 2 etc.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class multiOptionButton : MonoBehaviour
{
public Button myButton;
private string currentOption = "option 1";
// Start is called before the first frame update
void Start()
{
// set the initial text of the button
setButtonText(currentOption);
// add an event listener to look out for button clicks
myButton.onClick.AddListener(myButtonClick);
}
void myButtonClick()
{
switch (currentOption)
{
case "option 1":
// run stuff for option 1
Debug.Log("Doing option 1 things");
// change the current option for the next click
currentOption = "option 2";
// change the text on the button to be the next option
setButtonText(currentOption);
break;
case "option 2":
Debug.Log("Doing option 2 things");
currentOption = "option 3";
setButtonText(currentOption);
break;
case "option 3":
Debug.Log("Doing option 3 things");
currentOption = "No More!";
setButtonText(currentOption);
break;
}
}
void setButtonText(string buttonText)
{
myButton.transform.GetChild(0).GetComponent<Text>().text = buttonText;
}
}