OnClick Event in Unity

Gabriel Perez
2 min readJan 10, 2022

Setting up UI item selection from the Smuggler.

The goal is to have the player be able to select an item from the shop. So in that case, OnClick events in Unity will do the job!

I have the UI shop set up to have only three items from a smuggler within a mysterious cave.

In the shop vendor script, I want to create a new method for the selected item. It will have an integer as a parameter so that a value can be assigned to the inspector.

public void SelectItem(int item)
{
switch (item)
{
case 0:
_currentSelectedItem = item;
_currentItemCost = flameSwordCost;
break;
case 1:
_currentSelectedItem = item;
_currentItemCost = bootsOfFlightCost;
break;
case 2:
_currentSelectedItem = item;
_currentItemCost = keyToCastleCost;
break;
}
}

If the item selected is either 0, 1, or 2, then pass in the value of item to the _currentSelectedItem variable and pass in the item cost to the _currentItemCost variable.

This method will be called from OnClick(), a Unity Event method provided by the UI Button element in the inspector.

With my FlameSword UI Button selected, I can now assign the SelectedItem() method to the OnClick() and assign the value of 0. I do the same for the other two with their respective item value, Boots of Flight with a value of 1, and Key to Castle with a value of 2.

I added a Debug.Log(“Item Selected: “ + item) at the end of the SelectedItem() method to see in the Console that the item I clicked called the method from the OnClick() Unity Event.

And it does! As you can see, I also have a Buy and a Close button. They also use the OnClick() to call their respective behavior method from a script.

That is all for using the OnClick() event in Unity!

Gabriel

--

--

Gabriel Perez

Hello everyone, My name is Gabriel Perez, I am a Unity Developer and a creator who is always learning and experimenting.