I’ve tried to create a ‘dead body’ of my enemy cubie. (I’m using cubes to finish scripting first, later I’ll add models with animations etc., but I’m having one problem with it.)
Into the void Update() function. To constantly check the curHealth. But because I’ve putted it into the Update() function, it now creates the PrefabEnemy over and over again. How do I fix this? I need to disable the funtion once it has been run? And how do I do this?
You should not assign anything to PrefabEnemy at runtime! The way you’re doing this will append “(Clone)” to each new enemy, making incredibly long names!
In order to create a “dead body” to replace a dead enemy, you should have a different prefab, not reproduce the live enemy.
Declare a variable deadBody outside any function. When curHealth is zero and deadBody is null, create the dead body and assign its GameObject reference to deadBody - this way only the if code will be executed only once.
public deadBodyPrefab: GameObject; // drag the dead body prefab here
GameObject deadBody = null; // add this variable outside any function
public void OnEnemyKilled() {
if(curHealth == 0 && !deadBody){ // only create the dead body once
deadBody = Instantiate(deadBodyPrefab) as GameObject;
this.enabled = false;
enemyAI.enabled = false;
enemyAttack.enabled = false;
}
}
At the end of this if statement make curHealth = -1. That way any functions that really on this being a positive number aren’t negatively affected and since it no longer equals 0 it wont keep running the loop. Another way is to make an if statement inside of that statement that checks if the variable PrefabEnemy is created or not by simply doing…
what he is saying with the if(prefab) is basically you add another check.
The first check is to make sure the enemy is dead, the second check is to see if you’ve spawned the prefab to take care of that yet.
you start out with that equal to true, you dont have a prefab. Or if you use the existence of the prefab itself you do a if (!prefab) where you check for the NOT. A if false really.
then only when the enemy is dead AND things you do when enemy is dead hasn’t happened yet, do you do the things you do.
Once you do those things like spawning the prefab something should change so that the next loop the if statement catches the change and doesnt run again.