Points when an enemy dies.

So following up on my other question about making an enemy drop an item and then once the item is collected the score goes up. However, i would prefer it if when the enemy is destroyed i get points added onto the score, not having to collect something first.

A script would be great however an explination would be just as good.

Thanks in advance for any help.

The naive (but potentially entirely sufficient) solution to this would be to make the score a static variable somewhere (so that all scripts can easily access it), and simply check whether the enemy health is <= 0 in the enemy’s update function. If true, increase the score destroy the enemy’s gameObject.

The more sophisticated solution would be event-driven. I posted a mini-tutorial that coud easily be adapted in this answer: http://answers.unity3d.com/questions/251765/invoking-all-instances-of-a-non-static-function.html

You can achieve that in more than a way.

As a first method, I assume that the only way an enemy can be destroied is through a collision with the player (or a projectile shooted by the player, I think you’re making a FPS). So, you can attach something like this to the enemy (super-simple example):

function OnDestroy(){
   score++;
}

Obviously, this method will give at the player undeserved points, in case that the enemy dies after a collision with an obstacle on the scene, after the level completion…In other words, after a behaviour that doesn’t have to give points. Rougly speaking, you have a poor control about points assignment.


Another, more controlled way, would be the assignment of points after a particular collision. An example:

function OnCollisionEnter (theCollision : Collision) {
   if (theCollision.gameObject.tag == "Ammo"){ //Ammo is just an example
      score++;
      Destroy(gameObject); //this will destroy the enemy!
   }
}

So, my advice is to implement something similar to this last method. Hope this helps!