Trigger/Runtime/Collider/ColliderTriggerAreaBase.cs

50 lines
1.5 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using UnityEngine;
namespace Syntriax.Modules.Trigger
{
public abstract class ColliderTriggerAreaBase : MonoBehaviour, IColliderTriggerArea
{
[SerializeField] private LayerMask colliderMask = ~0;
protected Collider2D[] nonAllocResults = new Collider2D[32];
protected int previousTriggerCount = 0;
public LayerMask ColliderMask { get => colliderMask; set => colliderMask = value; }
public Action<List<Collider2D>> OnTriggeredCollidersUpdated { get; set; } = null;
public List<Collider2D> ColliderList { get; protected set; } = new List<Collider2D>(32);
protected abstract int TriggerCount { get; }
public virtual bool Check()
{
int triggerCount = TriggerCount;
2022-12-17 22:44:44 +03:00
if (!IsArrayAndListIdentical(triggerCount))
{
ColliderList.Clear();
for (int i = 0; i < triggerCount; i++)
ColliderList.Add(nonAllocResults[i]);
OnTriggeredCollidersUpdated?.Invoke(ColliderList);
}
previousTriggerCount = triggerCount;
return triggerCount > 0;
}
2022-12-17 22:44:44 +03:00
private bool IsArrayAndListIdentical(int triggerCount)
{
if (previousTriggerCount != triggerCount)
return false;
for (int i = 0; i < triggerCount; i++)
if (!ColliderList.Contains(nonAllocResults[i]))
return false;
return true;
}
}
}