Wednesday 4 March 2015

Events in Unity

Events are a useful tool for communicating between game objects, especially when you don't know which objects will be communicating with each other.

Say we have a Button. When the user clicks on the button, we want another Thing to do task X. Maybe the code would look like this:

void OnClick(){
     Thing.doX();
}

All very well. But what if we decide that actually, there's going to be a whole bunch of different Things in this scene, and they should all do X? What if those Things need more information to do X? What if the set of Things that should perform the task X is constantly changing?

If any of that is true, that means we'll have to change our code for the Button in order to change what and how Things do X. And all the while the button hasn't changed. It's still there, doing its thing, getting clicked by the user. So why should we have to change the Button, if the responsibilities of other objects have changed?

The answer is that we don't, if we use Events.

Events are a really handy construct. They can be thought of as a one-to-many relationship, where one object publishes or broadcasts events and a set of others receive and act on them. Just like a radio broadcaster doesn't know how many people are tuned in at any given time, the Event broadcaster doesn't know what objects are subscribed or even if any of them are.

So our button code would be changed to look something like this:


//This defines a delegate which is a little like a function pointer.
//It defines the kind of function that is needed to handle the event.
//In this case, a void function that takes an object is needed
//to properly handle this event. 
public delegate void ClickEventHandler(Object sender);

//This goes inside the Button class, and defines a delegate member of the ClicEventHandler type for that button.
//This is the event that other classes will listen to.
public event ClickEventHandler clickEvent;

 void OnClick(){
     //Now, when the button is clicked, all of the delegates subscribed to the event will trigger
    clickEvent(this);
}

public class Thing{
    public void handleButtonClick(Object sender){
        doX();
    }
}


Now, we can change the behaviour of the Thing without changing the button at all.

In Essence of Glory, events are used to update parts of the game engine about changes in other parts of it. For example, when a ship is moved in the Model, an event is raised that is received by the View, which then updates where that ship is displayed on the screen. Events can also be used for special effects that trigger under certain conditions.

More information about Events in C# can be found here and in Unity here.

No comments:

Post a Comment