InstantiatePrefab.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using UnityEngine;
  2. using UnityEngine.AI;
  3. public class InstantiatePrefab : MonoBehaviour
  4. {
  5. public GameObject prefabHuman;
  6. public GameObject waypoints;
  7. public int amount = 1;
  8. public int maxNumPerGroup = 5;
  9. public Vector3 spawnPoint;
  10. public Vector2 speedMinMax = new Vector2(4.0f, 7.0f);
  11. public Vector2 wanderTimerMinMax = new Vector2(10.0f, 15.0f);
  12. //Can be passed on
  13. [HideInInspector]
  14. public GameObject[][] humanObjs;
  15. [HideInInspector]
  16. public float[] wanderTimer;
  17. // Start is called before the first frame update
  18. void Start()
  19. {
  20. //Save all waypoints from GameObject into Transform array
  21. Transform[] wpArray = waypoints.GetComponentsInChildren<Transform>();
  22. Transform[] waypointsArray = new Transform[wpArray.Length - 1];
  23. for(int k = 1; k < wpArray.Length; k++)
  24. {
  25. waypointsArray[k - 1] = wpArray[k];
  26. }
  27. gameObject.GetComponent<WanderingAITest>().waypoints = waypointsArray;
  28. //Calculate number of groups
  29. int numGroups = 1;
  30. if(amount > 0)
  31. numGroups = (int) Mathf.Ceil((float)amount / (float)maxNumPerGroup);
  32. humanObjs = new GameObject[numGroups][];
  33. //Set wanderTimer
  34. wanderTimer = new float[humanObjs.Length];
  35. int humansLeft = amount;
  36. // instantiate humans, save in array and modifie
  37. for(int i = 0; i < humanObjs.Length; i++)
  38. {
  39. //Calculate Group Size
  40. int groupSize = (humansLeft > maxNumPerGroup) ? maxNumPerGroup : humansLeft;
  41. humanObjs[i] = new GameObject[groupSize];
  42. humansLeft -= groupSize;
  43. //Nav Mesh Agent - speed
  44. float speed = Random.Range(speedMinMax.x, speedMinMax.y);
  45. //Wandering AI Waypoints (Script)
  46. wanderTimer[i] = Random.Range(wanderTimerMinMax.x, wanderTimerMinMax.y);
  47. //target scattering
  48. // instantiate humans per group and save them in matrix
  49. for (int j = 0; j < humanObjs[i].Length; j++)
  50. {
  51. humanObjs[i][j] = Instantiate(prefabHuman, new Vector3(j + spawnPoint.x, 0, i + spawnPoint.z), Quaternion.identity, this.transform);
  52. humanObjs[i][j].tag = this.transform.tag;
  53. humanObjs[i][j].GetComponent<NavMeshAgent>().speed = speed;
  54. humanObjs[i][j].GetComponent<Animator>().speed = 0.5f + (speed / speedMinMax.y);
  55. }
  56. }
  57. }
  58. }