123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189 |
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class EnemyManager : MonoBehaviour
- {
-
-
-
- [Tooltip("The prefab used to spawn the enemy. Should contain a NavMeshAgent component. ")]
- public GameObject enemyPrefab;
-
-
-
- private bool isReady = false;
-
-
-
- private int noNavMeshCount = 0;
-
-
-
- private Vector3 centerNavMesh;
-
-
-
- private int agentTypeNavMeshID = 0;
-
-
-
- private int agentType = 0;
-
-
-
- static List<GameObject> enemies = new List<GameObject>();
- void Update()
- {
-
- if (isReady && enemies.Count == 0 && noNavMeshCount < 20)
- {
- Create();
- }
-
- if (enemies.Count > 0)
- {
- enemies.RemoveAll(item => item == null);
- }
- }
-
-
-
-
-
- void StartNavMesh()
- {
-
- Clear();
- isReady = false;
- }
- private void OnEnable()
- {
- NavMeshSurface.OnNavMeshReady += Ready;
-
- Component[] lights = enemyPrefab.GetComponentsInChildren(typeof(Light));
- foreach (Light l in lights)
- {
- if (!l.gameObject.GetComponent<ZEDLight>())
- {
- l.gameObject.AddComponent<ZEDLight>();
- }
- }
- }
- private void Start()
- {
- StartNavMesh ();
- UnityEngine.AI.NavMeshAgent c;
- if ((c = enemyPrefab.GetComponent<UnityEngine.AI.NavMeshAgent>()) != null)
- {
- agentType = c.agentTypeID;
- }
- }
- private void OnDisable()
- {
-
- NavMeshSurface.OnNavMeshReady -= Ready;
- }
-
-
-
-
-
-
-
- void Ready(object sender, NavMeshSurface.PositionEventArgs e)
- {
- centerNavMesh = e.position;
- isReady = e.valid;
- agentTypeNavMeshID = e.agentTypeID;
- Clear();
- }
- public void Ready()
- {
- isReady = true;
- Clear();
- }
-
-
-
- void Clear()
- {
- foreach (GameObject o in enemies)
- {
- Destroy(o);
- }
- enemies.Clear();
- }
-
-
-
-
- static void Destroyed(GameObject o)
- {
- enemies.Remove(o);
- }
-
-
-
- public void Create()
- {
-
- if (agentType != agentTypeNavMeshID)
- {
- Debug.LogWarning("The agent ID differs from the NavMesh");
- return;
- }
-
- enemies.Add(Instantiate(enemyPrefab, centerNavMesh, Quaternion.identity));
- List<GameObject> notActivated = new List<GameObject>();
-
- foreach (GameObject o in enemies)
- {
- NavMeshAgentController a = o.GetComponent<NavMeshAgentController>();
- if (a.Move())
- {
- a.GetComponent<RandomWalk>().Activate();
- noNavMeshCount = 0;
- }
- else
- {
- notActivated.Add(a.gameObject);
- noNavMeshCount++;
- }
- }
-
-
- foreach (GameObject o in notActivated)
- {
- Destroy(o);
- enemies.Remove(o);
- }
- }
- }
|