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

Headless, Python, and Flask: Massive Flexibility in a Microframework

Refactoring Ruby on Rails Controllers Using Blocks

The Beginner’s Guide to Version Control with GitHub

Streaming Data

Python Programming best books for Beginners

Python Programming best books for Beginners

Hybrid API Management Pattern

ALEO: The best of Maestro.

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

2D Mobile: Loot System

Point & Click to Move in Unity

Unity new Input System (Part I)

Intro Physics with Unity