Game Development Reference
In-Depth Information
Note The disadvantage to using C# properties in Unity, as opposed to using directly accessible public
variables, is their lack of visibility in the Object Inspector. In short, C# properties are always hidden to the
Object Inspector and so cannot be changed from the Editor. You can only access them from code.
This code is much better. It lacks an Update function and no longer wastes precious time executing
health validation code unnecessarily on every frame. Health validation has instead been shifted from
Update to the Set aspect of the Health property, which is executed only when the Health value is
changed. The Set function will be executed for every assignment to the Health variable (see Listing 3-3).
Listing 3-3. Setting Player Health: This Code Will Execute the Set Function for the C# Health Property
PlayerInstance.Health = 0;
This refined Player class is fine and functional insofar as it goes, but perhaps it doesn't go quite
far enough. Though this code is better at detecting and responding to health change events than
its previous incarnation, there's still a logistical problem we simply can't get around if we just go on
restricting our refinements to the Player class alone. Specifically, what should we do if a different
class (not the Player ) needs to detect and respond to Player health changes? For example, a
hypothetical GameManager class might need to know that when Player health reaches close to 0,
it needs to play a warning and alert sound. We could, of course, fix this in a specific and ad hoc
way by adding some extra code to the Player Health(Set) function, which notifies a separate
GameManager class about the health change event. This update might look like Listing 3-4.
Listing 3-4. Adapting the Player Class Health Change Event to Notify a Game Manager Class
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();
 
Search WWH ::




Custom Search