Game Development Reference
In-Depth Information
This code will work in the sense that it'll always detect when the Player's health falls to 0 or below,
and then initiates the appropriate death behavior as a response. However, the code is really not
efficient because it executes many more times than necessary. Specifically, on each and every frame
(which could be over 100 times per second ) the code always checks Player health, even if the health
has never changed since the last frame. The solution to this problem initially is simply to arrange our
code more effectively. On closer inspection, we see that the only time it's truly necessary to evaluate
Player health is when it changes, either when it increases or decreases; a health change event . At
no other time would it be necessary to check Player health, because we'd know that, without any
changes, it'd always be the same as when we last evaluated it.
So how could we recode this hypothetical Player class to support the proposed repair? One way
is to use accessor methods or C# properties . These are special kinds of functions that provide
controlled, public access to private variables or members of the class. It is a specific kind of
variable-function pairing in which the only way to set or read the variable is through its property
function, or accessor method. This means that every time the property function is called to set the
value for a private variable, we get the opportunity to execute behavior, including event functionality
and data validation. This is shown in action in Listing 3-2.
Listing 3-2. Using C# Properties to Detect Health Change Events
using UnityEngine;
using System.Collections;
public class Player : MonoBehaviour
{
//Properties to access and validate variable
public int Health
{
//If reading variable then return health
get {return iHealth;}
//Chang health value, now validate
set
{
//Update health
iHealth = value ;
//Check if player should die
if(iHealth <= 0)
Die();
}
}
//Private health variable
private int iHealth = 100;
public void Die()
{
//Handle Die Code Here
}
}
 
Search WWH ::




Custom Search