Creating a Call of Duty style zombie game. all zombies that spawn have the same animation controller and have three animations which are walking, attacking and falling/death. during testing with one zombie everything was working fine. when i then starting to spawn multiple zombies i found that only one of the zombies each wave would animate properly and the rest would only do the walking animation but neither the attacking or falling. here is the zombie manager script that is on every zombie that spawns, would be a great help if anyone could point me towards the best/correct way of resolving this issue:
public class ZombieManager : MonoBehaviour
{
Transform playerPos; // the players position
NavMeshAgent agent;
public int zombieHealth; // health of each zombie
public float sinkSpeed = 0.01f; // The speed at which the enemy sinks through the floor when dead.
static Animator zombieAnimator; // gain access to all animation for the zombies
// Use this for initialization
void Start ()
{
agent = GetComponent<NavMeshAgent>();
zombieAnimator = GetComponent<Animator> ();
playerPos = GameObject.FindGameObjectWithTag ("Player").transform; // get the players current position
}
// Update is called once per frame
void Update ()
{
if (zombieHealth > 0) // we only want to do stuff if the zombie is still alive
{
agent.SetDestination (playerPos.position); // have the zombie chase the player
if (Vector3.Distance (playerPos.position, this.transform.position) < 2) // the zombie can only attack if the player is within 2 units
{
zombieAnimator.SetBool ("isAttacking", true);
zombieAnimator.SetBool ("isWalking", false);
}
else // if the zombie is not attacking then make it use the walking animation
{
zombieAnimator.SetBool ("isAttacking", false);
zombieAnimator.SetBool ("isWalking", true);
}
}
else if (zombieHealth <= 0) // if the zombie no longer has any health the we can enter the DEATH state
{
ZombieDeath ();
}
}
public void ZombieDeath()
{
// turing all the other animations off and the falling one on
zombieAnimator.SetBool ("isAttacking", false);
zombieAnimator.SetBool ("isWalking", false);
zombieAnimator.SetBool ("isFalling", true);
GetComponent <UnityEngine.AI.NavMeshAgent> ().enabled = false; // Find and disable the Nav Mesh Agent.
GetComponent <Rigidbody> ().isKinematic = true; // Find the rigidbody component and make it kinematic (since we use Translate to sink the enemy).
StartCoroutine (zombieSinking()); // now that the zombie is DEAD, instead of just destroying it straight away we will have it sink beneath the ground
}
public IEnumerator zombieSinking()
{
yield return new WaitForSeconds(3f);
// ... move the enemy down by the sinkSpeed per second.
transform.Translate (-Vector3.up * Time.deltaTime/sinkSpeed);
yield return new WaitForSeconds(3f);
Destroy (gameObject);
}
}