Im spawning my enemy prefabs with code… and heres the script I have that handles those enemies:
- They all are using the same model and same animations, so I have created just 1 animation controller and linked that to all prefabs.
The problem im having is that this only makes 1 of the enemies animate -.-
using System.Collections;
using System.Collections.Generic;
using UnityEngine.AI;
using UnityEngine;
public class Enemy : MonoBehaviour {
static Animator anim;
NavMeshAgent navMeshAgent;
NavMeshPath path;
public float timeForNewPath;
bool inCoRoutine;
Vector3 target;
bool validPath;
// Use this for initialization
void Start () {
navMeshAgent = GetComponent<NavMeshAgent>();
path = new NavMeshPath();
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
if (!inCoRoutine)
StartCoroutine(DoSomething());
if (navMeshAgent != null) {
float velocity = navMeshAgent.velocity.magnitude;
if (velocity > 0) {
anim.SetBool("isWalking", true);
} else {
anim.SetBool("isWalking", false);
}
}
}
Vector3 getNewRandomPosition() {
float myX = gameObject.transform.position.x;
float myZ = gameObject.transform.position.z;
float x = Random.Range(-5, 5);
float z = Random.Range(-5, 5);
Vector3 pos = new Vector3(x+myX, gameObject.transform.position.y, z+myZ);
return pos;
}
IEnumerator DoSomething() {
inCoRoutine = true;
yield return new WaitForSeconds(timeForNewPath);
GetNewPath();
validPath = navMeshAgent.CalculatePath(target, path);
if (!validPath) Debug.Log("Found an invalid Path");
while (!validPath) {
yield return new WaitForSeconds(0.01f);
GetNewPath();
validPath = navMeshAgent.CalculatePath(target, path);
}
inCoRoutine = false;
}
void GetNewPath() {
target = getNewRandomPosition();
navMeshAgent.SetDestination(target);
}
}