﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Collider2D))]
public class RunMethodOnBounds : MonoBehaviour
{

    [SerializeField]
    LayerMask layerObjectToStore;
    [SerializeField]
    string methodCall;

    protected List<GameObject> insideMe = new List<GameObject>();
    // Use this for initialization

    public void Run()
    {
        foreach (GameObject obj in insideMe)
        {
            if (methodCall.Length > 0)
            {
                obj.SendMessage(methodCall, SendMessageOptions.DontRequireReceiver);
            }
        }
    }

    private void OnTriggerEnter2D(Collider2D coll)
    {
        if ((layerObjectToStore.value & 1 << coll.gameObject.layer) == 1 << coll.gameObject.layer)
        {
            if (!insideMe.Contains(coll.gameObject))
            {
                insideMe.Add(coll.gameObject);
            }
        }
    }

    private void OnTriggerExit2D(Collider2D coll)
    {
        if ((layerObjectToStore.value & 1 << coll.gameObject.layer) == 1 << coll.gameObject.layer)
        {
            if (insideMe.Contains(coll.gameObject))
            {
                insideMe.Remove(coll.gameObject);
            }
        }
    }
}
