Salder Salder - 3 months ago 20
C# Question

How do I make a GUI popup when I press a Button?

I am wondering how do I use onClick() or similar to make a GUI popup whenever I click on a button? Here is my current code. I am trying to implement the code into my shop script. The button the player would press is a button that says store. When the player presses the button named Store the script will make the actual shop show up. The Shop is not a separate scene. It is in one scene.

using UnityEngine;
using System.Collections;

public class Shop : MonoBehaviour
{

public int Money;
public int Trap = 0;
public int Weed = 0;

public GameObject ShopLocation;

void Start ()
{

Money = 100;
ShopLocation.gameObject.SetActive(false);
}

public void Clicked()
{

}

void OnTriggerExit()
{
ShopLocation.gameObject.SetActive(false);
}

public void trap()
{
if (Money >= 20) {
Money -= 20;
Trap += 15;
} else
{
print ("Not enough money for trap!");
}


}

public void weed()
{
if (Money >= 15) {
Money -= 15;
Weed += 10;
} else
{
print ("Not enough money for Weed!");
}
}
}

Answer

The Button component can be used to do this. Register to the Button event with Button.onClick.AddListener(()=>functionToCall()...).

using UnityEngine.UI;

public class Shop : MonoBehaviour 
{
    public GameObject shopToShow;

    public Button StoreButton;

    void OnEnable()
    {
        //Register Button Events
        StoreButton.onClick.AddListener(() => storeButtonCallBack());

    }

    private void storeButtonCallBack()
    {
        Debug.Log("Shop Button Clicked!");
        shopToShow.SetActive(true);
    }

    void OnDisable()
    {
        //Un-Register Button Events
        StoreButton.onClick.RemoveAllListeners();
    }
}

Remember, you must create a Button from the Editor and assign it to the StoreButton slot in the script. You should also put the UI to show when Button is clicked to the shopToShow slot.

Unity UI tutorial for you..