Newer
Older
HierarchicalFSM-Unity3D / Assets / Scripts / NPC / Sensors / Awareness.cs
  1. using System.Collections.Generic;
  2. using System.Collections;
  3. using UnityEngine;
  4. public class Awareness : MonoBehaviour
  5. {
  6. [Header("Aware Sensor Settings: ")]
  7. [SerializeField] private float radius;
  8. [SerializeField] private float delay; // Delay between sensor runs
  9. [SerializeField] private List<GameObject> targets = new List<GameObject>();
  10. [SerializeField] private LayerMask targetLayerMask;
  11. [SerializeField] private bool enable = true;
  12. [SerializeField] private string targetTag;
  13. public float Radius => radius;
  14. public bool Enable
  15. {
  16. get { return enable; }
  17. set
  18. {
  19. if (enable != value) // Check if the value is actually changing
  20. {
  21. enable = value;
  22. if (!enable)
  23. {
  24. targets.Clear(); // Clear the list only when transitioning to disabled
  25. }
  26. }
  27. }
  28. }
  29. public List<GameObject> TargetsList => targets;
  30. private void Start()
  31. {
  32. StartCoroutine(AwareRoutine());
  33. }
  34. private IEnumerator AwareRoutine()
  35. {
  36. while (true)
  37. {
  38. WaitForSeconds wait = new WaitForSeconds(delay);
  39. yield return wait;
  40. if (Enable)
  41. {
  42. GetTargets();
  43. }
  44. }
  45. }
  46. private void GetTargets()
  47. {
  48. targets.Clear();
  49. Collider[] colliders = Physics.OverlapSphere(transform.position, radius, targetLayerMask);
  50. foreach (Collider c in colliders)
  51. {
  52. if (c.gameObject.CompareTag(targetTag))
  53. {
  54. targets.Add(c.gameObject);
  55. }
  56. }
  57. if (targets.Count == 0)
  58. {
  59. Debug.LogWarning("There were no targets found in the current area!");
  60. }
  61. }
  62. public void SetTargetLayerMask(LayerMask mask)
  63. {
  64. targetLayerMask = mask;
  65. }
  66. public void SetTargetTag(string tag)
  67. {
  68. targetTag = tag;
  69. }
  70. }