Newer
Older
HierarchicalFSM-Unity3D / Assets / Scripts / NPC / Sensors / Awareness.cs
using System.Collections.Generic;
using System.Collections;
using UnityEngine;

public class Awareness : MonoBehaviour
{
    [Header("Aware Sensor Settings: ")]
    [SerializeField] private float radius;
    [SerializeField] private float delay;  // Delay between sensor runs
    [SerializeField] private List<GameObject> targets = new List<GameObject>();
    [SerializeField] private LayerMask targetLayerMask;
    [SerializeField] private bool enable = true;
    [SerializeField] private string targetTag;

    public float Radius => radius;

    public bool Enable
    {
        get { return enable; }

        set
        {
            if (enable != value)  // Check if the value is actually changing
            {
                enable = value;

                if (!enable)
                {
                    targets.Clear();  // Clear the list only when transitioning to disabled
                }
            }
        }
    }

    public List<GameObject> TargetsList => targets;

    private void Start()
    {
        StartCoroutine(AwareRoutine());
    }

    private IEnumerator AwareRoutine()
    {
        while (true)
        {
            WaitForSeconds wait = new WaitForSeconds(delay);
            yield return wait;

            if (Enable)
            {
                GetTargets();
            }
        }
    }

    private void GetTargets()
    {
        targets.Clear();
        Collider[] colliders = Physics.OverlapSphere(transform.position, radius, targetLayerMask);

        foreach (Collider c in colliders)
        {
            if (c.gameObject.CompareTag(targetTag))
            {
                targets.Add(c.gameObject);
            }
        }

        if (targets.Count == 0)
        {
            Debug.LogWarning("There were no targets found in the current area!");
        }
    }

    public void SetTargetLayerMask(LayerMask mask)
    {
        targetLayerMask = mask;
    }

    public void SetTargetTag(string tag)
    {
        targetTag = tag;
    }
}