using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.InputSystem; public class HerdController : MonoBehaviour { [SerializeField] private GameObject Prefab; [SerializeField] private int HerdCount = 50; [SerializeField] private Transform SpawnPoint; [SerializeField] private float WaitTime; private List Herd; void Start() { SpawnHerd(); StartCoroutine(MoveRoutine()); } //Recieved movement input from player private void OnMovement(InputValue value) { Vector2 input = value.Get(); Herd.ForEach(p => p.SetMovement(input)); } [ContextMenu("Spawn")] private void SpawnHerd() { float radius = 0; GameObject prefabExample = Instantiate(Prefab); Bounds bound = prefabExample.GetBounds(); Debug.Log(bound.size); Destroy(prefabExample); if (Herd != null) Herd.ForEach(p => Destroy(p)); Herd = new List(); for (int i = 0; i < HerdCount; i++) { int SpawnAttempt = 0; while (true) { Vector3 position = Vector3.ProjectOnPlane(Random.onUnitSphere, Vector3.up) * radius; Quaternion rotation = Quaternion.identity; if (SpawnPoint != null) position += SpawnPoint.position; if (SpawnPositionValid(position,rotation, bound)) { GameObject newObject = Instantiate(Prefab, position, rotation, transform); Herd.Add(newObject.GetComponent()); break; } SpawnAttempt++; if (SpawnAttempt % 10 == 0) { radius += bound.size.magnitude; } if (SpawnAttempt == 100) break; } Debug.Log("Total Spawned: " + Herd.Count); } } public IEnumerator MoveRoutine() { foreach (PlayerController pc in Herd) { pc.MoveObject(); } yield return new WaitForSeconds(WaitTime); StartCoroutine(MoveRoutine()); } private bool SpawnPositionValid(Vector3 position,Quaternion rotation ,Bounds bound) { Collider[] colliders = Physics.OverlapBox(position, bound.extents,rotation); Debug.DrawLine(position, position + Vector3.up); foreach(Collider col in colliders) { if (col.GetComponentInChildren()) return false; if (col.GetComponentInParent()) return false; } return true; } }