/* * author: ryan lin * date: 08/08/2024 * description: to cull and spawn AI people */ using System.Collections; using System.Collections.Generic; using UnityEngine; using Random = System.Random; /// /// to cull and spawn AI people /// public class AIManager : MonoBehaviour { /// /// a reference to the player /// public Transform player; /// /// the distance of which the AI would be "killed" /// public float cullingDistance; /// /// the prefab to spawn /// public GameObject aiPrefab; /// /// the maximum number of AI that can be spawned at any time /// public int maxAI; /// /// AI Spawn locations /// [SerializeField] private List aiSpawn; /// /// An array that contains the game objects of the AI objects /// private GameObject[] _ais; /// /// a temporary float to find the distance between the player and the AI /// private float _distance; /// /// to start the manager loop /// private void Start() { StartCoroutine(Manager()); } /// /// to show the range in the inspector when the object is selected /// private void OnDrawGizmosSelected() { Gizmos.color = Color.yellow; Gizmos.DrawWireSphere(player.position, cullingDistance); } /// /// to allow the IEnumerator to destroy or instantiate AI /// private IEnumerator Manager() { while (true) { // FIXME: feels weird _ais = GameObject.FindGameObjectsWithTag("AIs"); if (_ais.Length < maxAI) { var rand = new Random(); var spawnNo = rand.Next(0, aiSpawn.Count); var instance = Instantiate(aiPrefab, aiSpawn[spawnNo]); } foreach (var i in _ais) { _distance = Vector3.Distance(i.transform.position, player.position); if (_distance > cullingDistance) Destroy(i.gameObject); } yield return new WaitForSeconds(1); } } }