ExampleNavigator.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System.Collections;
  2. using UnityEngine;
  3. namespace Chronos.Example
  4. {
  5. // Example for Chronos with NavMeshAgents.
  6. // Will choose a random destination within a preset area at
  7. // a regular interval.
  8. [RequireComponent(typeof(UnityEngine.AI.NavMeshAgent))]
  9. public class ExampleNavigator : ExampleBaseBehaviour
  10. {
  11. // The delay between destination changes
  12. public float delay = 5;
  13. // The center of the potential destinations area
  14. public Vector3 areaCenter;
  15. // The size of the potential destinations area
  16. public Vector3 areaSize;
  17. private void Start()
  18. {
  19. // Start the coroutine
  20. StartCoroutine(ChangeDestinationCoroutine());
  21. }
  22. private IEnumerator ChangeDestinationCoroutine()
  23. {
  24. // Loop forever
  25. while (true)
  26. {
  27. // Choose a new destination
  28. ChangeDestination();
  29. // Wait for the delay, taking in consideration
  30. // the time scales. Notice "time.WaitForSeconds"
  31. // instead of "new WaitForSeconds"
  32. yield return time.WaitForSeconds(delay);
  33. }
  34. }
  35. private void ChangeDestination()
  36. {
  37. // Choose a new destination within the potential area
  38. Vector3 randomDestination = new Vector3()
  39. {
  40. x = areaCenter.x + Random.Range(-areaSize.x, +areaSize.x) / 2,
  41. y = areaCenter.y + Random.Range(-areaSize.y, +areaSize.y) / 2,
  42. z = areaCenter.z + Random.Range(-areaSize.z, +areaSize.z) / 2,
  43. };
  44. // Set it to the nav mesh agent
  45. GetComponent<UnityEngine.AI.NavMeshAgent>().SetDestination(randomDestination);
  46. }
  47. // Draw the area gizmos for easy manipulation
  48. private void OnDrawGizmos()
  49. {
  50. Gizmos.color = Color.magenta;
  51. Gizmos.DrawWireCube(areaCenter, areaSize);
  52. }
  53. }
  54. }