- Home /
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.
Answer by Drakestar · May 22, 2012 at 07:52 PM
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
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
Answer by BiG · May 22, 2012 at 07:55 PM
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!
Ah, yes: In my simple example, I also assume that the enemies die after one shot. You have to add the control over their life remaining, if they have an health bar.
when you put score++;
won't it just keep adding to infinity?
Yes, but only one point per kill. It won't keep adding unless you kill an enemy.