Spawned prefabs are sharing variables values
I'm trying to make a FPS with zombies but i have a problem when i try to decrease zombie health. I attached to zombie prefab this script:
using UnityEngine;
using System.Collections;
public class ZombieHealth : MonoBehaviour
{
private int health;
private bool isDead;
private Animator animator;
private int count;
void Awake ()
{
animator = GetComponent<Animator> ();
health = Random.Range (75, 125);
}
IEnumerator OnTriggerEnter (Collider collider)
{
if (collider.tag == "Bullet" && isDead == false)
{
Destroy (collider.gameObject);
health -= 10;
count++;
Debug.Log ("Health: " + health + "; Fire no:" + count);
if (health <= 0)
{
isDead = true;
animator.SetTrigger ("dead");
yield return new WaitForSeconds (5);
Destroy (this.gameObject);
}
}
}
}
I'm spawnig zombies at an interval adn first one has helth for example 102 (sometimes die when it has 2 health, idk why) an if i let firs zombie with 42 health and shoot another zombie 4 or 5 times that one dies and after that every spawned zombie die at first shot and it's also playing dying animation if i shoot in him even if he is dead and isDead variable is true.
What can I do to correct the script?
P.S. I start unity 2 week ago so i'm still kind of noob.
EDIT: in console is showing the correct values
Spawn code:
using UnityEngine;
using System.Collections;
public class ZombieSpawner : MonoBehaviour
{
public GameObject[] zombie;
public float spawnTime = 3f;
public Transform[] spawnPoint;
public static bool spawn;
void Start ()
{
InvokeRepeating ("Spawn", spawnTime, spawnTime);
}
void Spawn ()
{
if (spawn)
{
int zombieIndex = Random.Range (0, zombie.Length);
int spawnIndex = Random.Range (0, spawnPoint.Length);
Instantiate (zombie[zombieIndex], spawnPoint [spawnIndex].position, spawnPoint [spawnIndex].rotation);
}
}
}
Answer by FortisVenaliter · Jun 09, 2016 at 05:55 PM
Are you instantiating your zombies from a prefab, or are you instantiating them from the reference of the first zombie?
If it's the latter, then they will always copy the values at time of instantiation.