Destroying GameObject After Instantiate
So, I have a bit of an issue, I'm currently got this "Spawner" script which spawns Instantiate a prefab every second. Each prefab has a "Health" script.
The problem I am facing is, when the Health is at 0, and I call "Destroy(this.gameObject);" it always destroys the objects in the order that they was spawned in. So if I spawn 5, and I shoot the 5th one till its health is 0, it destroys the 1st one spawned.
If I have to provide the scripts I will do. Thank you if you can help me!
Enemy Health Script - http://pastebin.com/gVj7kcQk
Spawner Script - http://pastebin.com/qMue6Z9C
If this helps. This is the shoot script!
Shoot Script - http://pastebin.com/agLZVrHS
Answer by Zoogyburger · Apr 20, 2016 at 01:24 AM
Try your script like this:
{
//Shared Values
static float health = 100; //Enemys Health
static public bool dead = false; //Is the Enemy dead?
static public void TakeDamage() //
{
health -= 25;
//Debug.Log("Taken damage");
}
void Update()
{
if (health <= 0) // If the enemy health is
{ // 0 then it destroys the
Destroy(gameObject); //Destroys the enemy
}
if (health >= 101) //Makes sure that
{ //Health does not
health = 100; //go above 100
} //so no problems with op zombies
}
void OnTrigger(Collider other) //If it collides with player
{
if (other.gameObject.tag == "Player") //if it does collide with the player
{
//Debug.Log("Hitting Player"); //Tells you in the console
Health.Takeaway(); //Takes player health away through other script
}
}
}
Unfortunately this doesn't work. Removing the "Health = 100" makes everything just despawn, so it kills everything.
So basically, when I hit the Zombie. It takes the health away on every single cube. Then when the health is 0. It destroys the prefab so everything dies & nothing respawns because the prefab is destroyed.
Thank you for replying though.
I have the static values so other scripts can access them
static - the same variable is shared by ALL instances of the class that are created, and can be private, protected or public. $$anonymous$$eaning all prefabs will be destroyed since all of them are linked by static. You still can access these values without them being static. By
private EnemyHealth eh;
eh = FindObjectOfType<EnemyHealth> ();
and you can use the values by
eh.health
No worries, I got it. I did this though ins$$anonymous$$d -
eh = hit.transform.GetComponent<EnemyHealth>();
but it works!
Thank you. I really do appreciate it!
So do I add this to my "Shoot" script? As Such -
Thanks
You should put:
eh = FindObjectOfType<EnemyHealth>();
under void Start() do it's not finding the script every update. Other than that you are using it correctly. Just eh.anyVariableInScript should work perfectly fine
I added it in the update function, so when you fire the raycast and it hits and enemy, it will get the script for that enemy & then I can do things to that enemy? Otherwise wouldn't it just get 1 of the zombies health script until it dies