OnClick Event in Unity

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

--

--

--

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

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

The Elephant in the PostgreSQL

PostgreSQL

Sand Filled Pitch Maintenance in Rudhall #Sand #Filled #Pitch #Maintenance #Rudhall https://t.co/AXw

Strengths finder

Top 3 WebSocket Libraries For Real-Time Apps

Machine Learning for JavaScript Developers TensorFlow.js

Design and Development of Toy OS for teaching operating system-I

Creator Spotlight: MistaPotta Q&A

Bridge Detailing 2.0: Computational Modeling Methods Using Civil 3D, Revit, and Dynamo

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gabriel Perez

Gabriel Perez

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

More from Medium

Light layers in Unity HDRP

More Productive Editor Layout in Unity

P4: Creating a Gritty Office Den

Cinemachine and Group Targets in Unity