OnClick Events in Unity

addam davis
3 min readDec 15, 2021

--

Objective: Learn how to create OnClick events with our shop keeper!

Now that we have a shop panel set up we can create some functionality for our players to use. Specifically in this tutorial I am going to show you how to create simple OnClick events.

An OnClick event is essentially a function a button can call when the button is selected. To begin we need to create a script for our shop keeper.

In this script we are going to need a short list of variables. We need a public GameObject for the actual shop panel we created in the last tutorial. We need an int for the item our player selects and an int for the cost of the item selected. An int for the players gem count and finish it off with a reference to the player.

We want to open this shop by having our player run into the shop keeper. To do this we need an on trigger enter 2D method and we need to check for the player. We can set the player and activate the panel.

This means when we walk into the shopkeeper the shop panel will appear. To exit we can walk away from the shop keeper using on trigger exit.

We are now ready to set up our OnClick events. We need a method on the shopkeeper to handle these events.

we have three items/buttons in the shop and we are going to use the item variable to store the item ID.

Going into Unity, select the Flaming_Sword_Button. In the inspector thre is an On Click(). Press the plus button.

the (object) is the shop keeper.

Select no function — shopkeeper- select item(int)

Then we can assign an int to the item.

Do this for all three item buttons, with fire sword being =0, boots =1, key =2. Now when we test our game and we select the button the console will print out the item’s int.

We can use these OnClick events to select our items and with only a little further work these events would allow us to “purchase” these items. The buy item button could use an OnClick event to call a buy item method which we may cover in the near future. Now you know how to set up OnClick events! Don’t be afraid to experiment with your OnClick events and I’ll see you in the next tutorial!

--

--