Unity3D – Tutorials – UI – Button – OnClick

This feature is avaiable for Unity3D 4.6 or above.

Create Objects

1. Open Unity3D and create:

– MAIN TOP MENU> GameObject> Camera, name it ‘Main Camera’
– MAIN TOP MENU> GameObject> UI> Canvas
– MAIN TOP MENU> GameObject> UI> Button, this will add an ‘EventSystem’ and Button will be child of Canvas

NOTICE: Canvas will be created inside Layer UI

NOTICE: In the Hierarchy there is:
– Canvas
-> Button (it is the child of Canvas)
->> Text (it is the child of Button)

Setup Viewports and Tools

2. 3D Viewport select orthographic X View
3. TOP LEFT> TOOLS> Canvas Manipulation icon
4. Game Viewport> 4:3

On Click() – Ready to use function

The UI Framework contains a powerful event system, let’s take a first look.

1. Hierarchy> select Button> Inspector> Button (Script)

> Interactable: check

> On Click> click on ‘+’ Add List

a. DRAG AND DROP The Main Camera over the empty slot

b. RIGHT ROLLOUT> GameObject> SetActive> uncheck (it means false)

c. Play and click the button to deactivate Main Camera

On Click() – Custom function

Elegible Functions

NOTICE: a function will be elegible if is – public void MyFunction() – and have none or 1 parameter.

public: deve essere pubblica, cioè poter essere letta al di fuori dello script originale
void: non restituisce un valore di ritorno, non ammette il comando – return –

The parameter can be in C#:

– public void MyFunction()
– public void MyFunction(float MyFloat)
– public void MyFunction(int myInt)
– public void MyFunction(string myString)
– public void MyFunction(bool myBool)
– public void MyFunction(Object myObject) -> Unity Object

The parameter can be in JS:

– public function MyFunction()
– public function MyFunction(float MyFloat)
– public function MyFunction(int myInt)
– public function MyFunction(string myString)
– public function MyFunction(bool myBool)
– public function MyFunction(Object myObject) -> Unity Object

1. Attacch to Main Camera MyCameraScript.js:


#pragma strict

function Start () {
}

public function MyFunction(){
Debug.Log ("Clicked!");
}

function Update () {
}

2. Hiearchy> select Button> Inspector> Button (Script)> OnClick()> DRAG AND DROP The Main Camera over the empty slot

3. RIGHT ROLLOUT> GameObject> MyCameraScript> MyFunction

4. Play and click the Button