Game Development Reference
In-Depth Information
public int currScore = 0;
private TextMesh scoreMesh = null;
void Start()
{
scoreMesh = gameObject.GetComponent<TextMesh>();
scoreMesh.text = "0";
}
void OnEnable()
{
EnemyControllerScript.enemyDied += addScore;
}
void OnDisable()
{
EnemyControllerScript.enemyDied -= addScore;
}
void addScore(int scoreToAdd)
{
currScore += scoreToAdd;
scoreMesh.text = currScore.ToString();
}
}
You may notice that in the preceding script, we are listening to the
enemyDied
event
on the
EnemyControllerScript
. What we did here was we allowed other objects to
easily create scoring events that the
Score
object can optionally listen to. There is lots
of power to this!
Let's add that event and delegate to the enemy. Open up
EnemyControllerScript
,
and in the beginning, add the following code:
// States to allow objects to know when an enemy dies
public delegate void enemyEventHandler(int scoreMod);
public static event enemyEventHandler enemyDied;
Then, down in the
hitByPlayerBullet
function, add the following code just above
Destroy(gameObject,0.1f);
, right around line 95:
// Call the EnemyDied event and give it a score of 25.
if(enemyDied != null)
enemyDied(25);