Click A Button in Unity UI- Game Dev Series 109

Objective: using OnClick() event in shop system.

OnClick event is a function that makes UI button would work.
In this article, we will make a simple shop UI works by using OnClick event.


Let’s assume that we already have a shop system. We need to purchase some items from it. We need to select(click) the one we need, and click “Buy” to purchase it.

In this shop, the system should detect which item we selected and underline it as mark. Then when Player click “Buying Item”, it should cost the gems from Player to finish purchase.

Build item select function

Let’s create a function for those item buttons. To build a function that would make these buttons work, you need to add it to a relative script. In my game, I would create a function in ShopSystem script.

First create a SelectItem() method. Totally we have 3 items can be choose, which we can pass in an integer as button ID to identify these items.

We can back to editor and drag the gameobject that contain this script to OnClick() column of those buttons.

Then we can assign different ID to these buttons in the item column.

Once it done, back to ShopSystem script and set the condition to different by using switch statement.

In each case, we can call UIManager to adjust the underline position as selection mark, then we can set item cost to them too.

Once done, we can into Play mode to test this out.

Buy item button

Now we need to make the Buy Item button workable. It would be the same idea except it would need to do some calculation.

Create another method to Buy Item button. Inside this button we will compare the price of item we selected and the money we have.

In the Player script, I create a method called PurchasedDiamondCount(int) to do the calculation.

And again drag the shop gameobject to OnClick function of Buy Item button, then select BuyingItem().

That’s all! Now we increase the diamond count to Player and test our shop system.

And that is how to use OnClick() event to process the code.



A passionate gamer whose goal is to work in video game development.

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
S.J. Jason Liu

A passionate gamer whose goal is to work in video game development.