OnClick events in Unity
Another great feature inside the Unity Engine is the capability to create custom events.
Note: You should use the UnityEngine.Events namespace.
This is how you create a custom event throught code.
Why I’m I explaining custom events if this is a Guide specific for the OnClick event?
That’s because the OnClick event is exactly a custom event but with the only difference that is triggered when the mouse is pressed in some button nor UI Element.
Creating a Button
To Create a Button Element right click in the Hirarchy window and go to :
UI > BUTTON
Once the button is created we can see in the inspector the Button component and find for the OnClick event.
But how does this works?
Ok, let’s make an example. Let’s desactivate an object once the button is clicked.
If We click in the “+” button inside the event view, it will let us register a callback.
Now, select a random object in Unity and drag it into the event.
Once we do that, we can now press play and click our button. The player will disappear from the scene when the event releases.