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

public class Explosive : MonoBehaviour {

    public float damage;

    public LayerMask explosionMask;

    public float range = 3f;

    public GameObject explosionParticle;

	// Use this for initialization
	void Start () {
        GameObject.Destroy(gameObject, 5);
    }

    private void OnTriggerEnter(Collider other)
    {
        if (gameObject == null)
            return;

        Collider[] colliders = Physics.OverlapSphere(transform.position, range, explosionMask);

        HashSet<Monster> hitMonsters = new HashSet<Monster>();

        if (colliders != null && colliders.Length > 0)
        {
            for (int i = 0; i < colliders.Length; i++)
            {
                Monster monster = colliders[i].GetComponentInParent<Monster>();
                if (monster != null && !hitMonsters.Contains(monster))
                {
                    monster.TakeDamage(damage);
                    hitMonsters.Add(monster);
                }
            }
        }

        GameObject.Instantiate(explosionParticle, transform.position, Quaternion.identity);

        GameObject.Destroy(gameObject);
    }
}
