Game Development Reference
In-Depth Information
Planning Event Handling
Before jumping into coding an event-handling system, or any functionality for that matter, it's a
good idea to plan and think ahead. This reduces our chances of making mistakes and wasting time.
Of course, it doesn't eradicate our chances entirely! In this chapter, we'll code a dedicated event-
handling class, and there are strong reasons for doing this. Rather than list them, let's see what they
are in practice . Specifically, let's consider some “simpler” and alternative ways of handling events,
and examine the attendant problems or limitations associated with them.
Perhaps the simplest method to event handling is to forget about creating a dedicated class
altogether, and to code event-handler functionality directly into all the classes that need it. For
example, let's imagine we need to detect an event, such as when Player health falls to 0 or below, so
we can kill the Player and display a “Game Over” message. The event is when Player health falls to 0
or below , and the response is die and show “Game Over” . This kind of functionality could be coded
into the Player class, as shown in Listing 3-1.
Listing 3-1. Player Class Detecting Death Events
using UnityEngine;
using System;
//Player class
public class Player: MonoBehaviour
{
//[...] Other stuff declared here
//Health variable
public int Health = 100;
//[...] Other functions would be included here
//Update function called on each frame
void Update()
{
//Check player health
If(Health <= 0)
Die(); //Is <= 0, then run death functionality
}
}
Note The class coded in Listing 3-1, and in subsequent parts of this section, is hypothetical only. That is,
it's an imaginary class used merely to demonstrate a point. It's not necessary to code this class yourself or to
include it in the final CMOD project.
 
 
Search WWH ::




Custom Search