- Home /
Different Enemy Lives JavaScript
Currently I'm designing a game with 3 types of enemies 1 - Pink, 1 - Blue, 1 - Red. I have my player character shooting at the enemies and they are supposed to be destroyed if they are hit by the player's bullet. Currently this works, however, I want the Pink one to be destroyed after 1 shot, blue after 2 shots, red after 3 shots. In the game right now, if you shoot a blue enemy, a pink enemy is destroyed because the game is recognizing different enemies. So, what I'm asking is, how can I make it so that my game can differentiate between the different types of enemies and then, if a bullet hits JUST THAT SPECIFIC ENEMY, have that enemy's lives decrease/have it be destroyed. Also, I created 3 different enemy objects that are tied to different tags, but for some reason, the code that follows isn't recognizing that. It's recognizing that they are all the same GameObject and destroying them anyway. Here's the code I'm working with:
var enemies : GameObject[];
var pinkLives = 1;
var blueLives = 2;
var redLives = 3;
var timesHit = 0;
//var enemyArray = new Array();
//enemyArray.length = 3;
function Start () {
}
function Update () {
}
function OnTriggerEnter(collision:Collider) {
if(GameObject.FindGameObjectWithTag("Enemy_Pink")) {
if(collision.gameObject.tag == "Bullet") {
pinkLives--;
if(pinkLives == 0) {
Destroy(GameObject.Find("Enemy_Pink"));
}
}
}
if(GameObject.FindGameObjectWithTag("Enemy_Blue")) {
if(collision.gameObject.tag == "Bullet") {
blueLives--;
if(blueLives == 0) {
Destroy(GameObject.Find("Enemy_Blue"));
}
}
}
if(GameObject.FindGameObjectWithTag("Enemy_Red")) {
if(collision.gameObject.tag == "Bullet") {
redLives--;
if(redLives == 0) {
Destroy(GameObject.Find("Enemy_Red"));
}
}
}
Destroy(collision.gameObject);
}
Answer by getyour411 · Mar 06, 2014 at 12:52 AM
I'm assuming you have this script attached to all three enemies. Change
if(GameObject.FindGameObjectWithTag("...")
to
if(gameObject.name == "...")
Note that this approach in general isn't optimal, consider setting the # of lives as public/set on each instance (unless Pink really needs to know when Blue dies)
"Also, I created 3 different enemy objects that are tied to different tags, but for some reason, the code that follows isn't recognizing that. It's recognizing that they are all the same GameObject and destroying them anyway."
That's because your FindGameObjectWithTag is not limited by your OnTrigger criteria, so it's going to find all instances in the hierarchy. With a litte rework, you would not need any of the IF gameObject Pink/Blue/Green stuff at all