Unity UI Button
The button UI element in unity responds to a click from the user and is used to initiate or confirm an action. Some common examples are: Submit, Ok, and Cancel buttons.
To insert a button element, right in the scene hierarchy, and select GameObject -> UI -> Button. If you don't have an existing canvas and an EventSystem, Unity will automatically create one for you, and place the button inside the canvas as well.
When you play the scene, you will notice that the button already has some standard functionality, such as detecting when the mouse is hovering over it and changing color when you pressed that button.
First of all, create a script file, and rename it to ButtonActions.cs
This script specified a simple method that logs how many times we have hit the button.
Now, create an empty GameObject and attach this script file to it. We do this because a button will not do anything on its own; it only calls the specified method in its scripting.
Now, select the Button, and go to the Inspector tab and search for OnClick() property.
Click on that + icon on the bottom tab, and when you click, a new entry should show up in the list.
This entry defines what object the button press acts on, and what function of that object's script is called. Because of the event system used in the button press, you can generate multiple functions simply by adding them to the list.
Drag and drop the empty GameObject, which contains the ButtonGameObject script we created, onto the None (Object) slot.
Navigate the 'No Function' dropdown list, and look for our OnButtonPress method. For that, go to your Script file name (ButtonAction) and select OnButtonPress () method.
When you play the game now, you can test the button, the console prints out how many times you have pressed the button.