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;
  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 { enable = value;}
  18. }
  19. public List<GameObject> TargetsList => targets;
  20. private void Start()
  21. {
  22. StartCoroutine(AwareRoutine());
  23. }
  24. private IEnumerator AwareRoutine()
  25. {
  26. while (true)
  27. {
  28. WaitForSeconds wait = new WaitForSeconds(delay);
  29. yield return wait;
  30. if (Enable)
  31. {
  32. GetTargets();
  33. }
  34. }
  35. }
  36. private List<GameObject> GetTargets()
  37. {
  38. Vector2 vec = new Vector2(transform.position.x, transform.position.z);
  39. Collider2D[] collider = Physics2D.OverlapCircleAll(vec, radius, targetLayerMask);
  40. List<GameObject> targets = new List<GameObject>();
  41. if (collider.Length != 0)
  42. {
  43. foreach (Collider2D c in collider)
  44. {
  45. if (c.gameObject.tag == targetTag)
  46. {
  47. targets.Add(c.gameObject);
  48. }
  49. }
  50. return targets;
  51. }
  52. else
  53. {
  54. Debug.LogWarning($"There were no cover objects found in the current area!");
  55. return null;
  56. }
  57. }
  58. public void SetTargetLayerMask(LayerMask mask)
  59. {
  60. targetLayerMask = mask;
  61. }
  62. public void SetTargetTag(string tag)
  63. {
  64. targetTag = tag;
  65. }
  66. }