123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- using UnityEngine;
- using UnityEngine.AI;
- public class InstantiatePrefab : MonoBehaviour
- {
- public GameObject prefabHuman;
- public GameObject waypoints;
- public int amount = 1;
- public int maxNumPerGroup = 5;
- public Vector3 spawnPoint;
- public Vector2 speedMinMax = new Vector2(4.0f, 7.0f);
- public Vector2 wanderTimerMinMax = new Vector2(10.0f, 15.0f);
- //Can be passed on
- [HideInInspector]
- public GameObject[][] humanObjs;
- [HideInInspector]
- public float[] wanderTimer;
- // Start is called before the first frame update
- void Start()
- {
- //Save all waypoints from GameObject into Transform array
- Transform[] wpArray = waypoints.GetComponentsInChildren<Transform>();
- Transform[] waypointsArray = new Transform[wpArray.Length - 1];
- for(int k = 1; k < wpArray.Length; k++)
- {
- waypointsArray[k - 1] = wpArray[k];
- }
- gameObject.GetComponent<WanderingAITest>().waypoints = waypointsArray;
- //Calculate number of groups
- int numGroups = 1;
- if(amount > 0)
- numGroups = (int) Mathf.Ceil((float)amount / (float)maxNumPerGroup);
- humanObjs = new GameObject[numGroups][];
- //Set wanderTimer
- wanderTimer = new float[humanObjs.Length];
- int humansLeft = amount;
- // instantiate humans, save in array and modifie
- for(int i = 0; i < humanObjs.Length; i++)
- {
- //Calculate Group Size
- int groupSize = (humansLeft > maxNumPerGroup) ? maxNumPerGroup : humansLeft;
- humanObjs[i] = new GameObject[groupSize];
- humansLeft -= groupSize;
- //Nav Mesh Agent - speed
- float speed = Random.Range(speedMinMax.x, speedMinMax.y);
-
- //Wandering AI Waypoints (Script)
- wanderTimer[i] = Random.Range(wanderTimerMinMax.x, wanderTimerMinMax.y);
- //target scattering
- // instantiate humans per group and save them in matrix
- for (int j = 0; j < humanObjs[i].Length; j++)
- {
- humanObjs[i][j] = Instantiate(prefabHuman, new Vector3(j + spawnPoint.x, 0, i + spawnPoint.z), Quaternion.identity, this.transform);
-
- humanObjs[i][j].tag = this.transform.tag;
- humanObjs[i][j].GetComponent<NavMeshAgent>().speed = speed;
- humanObjs[i][j].GetComponent<Animator>().speed = 0.5f + (speed / speedMinMax.y);
- }
- }
- }
- }
|