StartButton
Button Component UnityEvent
Last updated
Button Component UnityEvent
Last updated
UI Buttons can be configured to execute a public method when the Button's OnClick Event occurs.
Create a UI Button
it will also have a child-gameObject that is UI Text
Rename the Button to StartButton
Set the RectTransform to position the StartButton.
In the Inspector, make sure to set both Normal and Highlighted Colors
Set Navigation to None
Notice that OnClick( ) has: List is Empty
UI-Button Components have an associated UnityEvent: onClick.
The Button Component can be considered as using the Observer Pattern. The Observer pattern provides a method to decouple logic when 2 objects need to communicate with each other.
In our case, the Button is the Event Subject or Publisher, our custom MiniGameManager script is the Event Listener. We must define a public method in the MiniGameManager class, to define a Listener method which will be configured to be executed when the Publisher's onClick event is invoked.
OnClick is a UnityEvent, it maintains a list of all Listener methods to be executed when the OnClick event is invoked. The Listener object must define a public method to be added as a listener to the Button's onClick Event list of listeners.
Game Programming Patterns: Observer Pattern
The observer pattern lets one piece of code announce that something interesting happened without actually caring who receives the notification.
In the code below, we have defined a function that we want to have executed when the button OnClick() event occurs. :
public void GameStartActions(){ //do game start things }
It is required that our function match the onClick event's delegate-type: in this case, a public method with a void return-type and no input parameters, in order to add our GameStartActions() method as a listener to the button's onClick event.
When the button object is clicked, we want our custom script component to be notified, we do so by creating a public method that is passed as a delegate to the button's onClick event. A Delegate provides a way to create a reference-type that refers to a method instead of a variable or object. Note, we're passing a method itself into the AddListener( ) method of the onClick event.