Hark-the-Moon-Men-Cometh / Assets / Scripts / TemporaryDamageSource.cs
TemporaryDamageSource.cs
Raw
using System.Collections.Generic;
using UnityEngine;

public class TemporaryDamageSource : MonoBehaviour, IDamageSource
{
    public List<GameObject> i_sources { get => m_sources; 
        set => m_sources = value; }
    public float i_damage { get => m_damage; set => m_damage = value; }

    public float m_timeToLive;
    private float m_lifeTimer;
    public int m_maxCollisions;
    private int m_collisionCounter;

    [SerializeField]
    private List<GameObject> m_sources;
    [SerializeField]
    private float m_damage;
    private List<IHarmable> m_harmedThisAttack;

    void Awake()
    {
        m_collisionCounter = 0;
        m_lifeTimer = 0;
        m_sources = new List<GameObject>();
        m_harmedThisAttack = new List<IHarmable>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        m_lifeTimer += Time.deltaTime;
        if (m_lifeTimer > m_timeToLive) 
        { 
            Destroy(this.gameObject);
        }
    }

    public void InflictDamage(IHarmable target)
    {
        Debug.Log(target);
        Debug.Log(m_harmedThisAttack);
        if (!m_harmedThisAttack.Contains(target))
        {
            m_harmedThisAttack.Add(target);
            target.TakeDamage(m_damage);
        }
    }

    public void HarmOther(GameObject other)
    {
        IHarmable harmable = other.GetComponent<IHarmable>();
        if (harmable != null && !m_sources.Contains(other))
        {
            InflictDamage(harmable);
        }
    }

    private void OnCollisionEnter(Collision collision)
    {        
        HarmOther(collision.gameObject);
        CheckCollisionCount(collision.collider);
    }

    private void OnTriggerEnter(Collider other)
    {
        HarmOther(other.gameObject);
        CheckCollisionCount(other);
    }

    //This allows, e.g. a bullet to go through multiple enemies
    public void CheckCollisionCount(Collider other)
    {
        if(!m_sources.Contains(other.gameObject))
        {
            m_collisionCounter++;
        }
        if(m_collisionCounter >= m_maxCollisions)
        {
            Destroy(this.gameObject);
        }
    }
}