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;
    [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 == false)
            {
                targets.Clear();
            }

            enable = value;
        }
    }

    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 List<GameObject> GetTargets()
    {
        Vector2 vec = new Vector2(transform.position.x, transform.position.z);
        Collider2D[] collider = Physics2D.OverlapCircleAll(vec, radius, targetLayerMask);
        List<GameObject> targets = new List<GameObject>();

        if (collider.Length != 0)
        {
            foreach (Collider2D c in collider)
            {
                if (c.gameObject.tag == targetTag)
                {
                    targets.Add(c.gameObject);
                }
            }

            return targets;
        }

        else
        {
            Debug.LogWarning($"There were no cover objects found in the current area!");
            return null;
        }
    }

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

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