본문 바로가기
프로그래밍/C#

버프 시스템 클래스

by neive 2022. 5. 27.
728x90
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.AsyncOperations;

public struct BuffData
{
    public Soul owner;
    public float lifeTime;
    public Action onEnd;

    public BuffData(Soul owner, float lifeTime, Action onEnd)
    {
        this.owner = owner;
        this.lifeTime = lifeTime;
        this.onEnd = onEnd;
    }
}

public class Buff : MonoBehaviour
{
    private Dictionary<int, BuffData> m_Dic_Buff = new Dictionary<int, BuffData>();
    private Dictionary<int, GameObject> m_Dic_Effect = new Dictionary<int, GameObject>();

    public void OnUpdate(float deltaTime)
    {
        foreach (var key in m_Dic_Buff.Keys.ToList())
        {
            var data = m_Dic_Buff[key];

            if (!data.owner.IsLive())
                data.lifeTime = 0.0f;
            
            data.lifeTime -= deltaTime;
            if (data.lifeTime <= 0)
                Del(key);
            else
                m_Dic_Buff[key] = data;
        }
    }

    public void Add(Soul owner, int index, float lifeTime, Action startAction, Action endAction)
    {
        if (m_Dic_Buff.ContainsKey(index))
            m_Dic_Buff[index] = new BuffData(owner, lifeTime, endAction);
        else
        {
            AttachEffect(index);
            m_Dic_Buff.Add(index, new BuffData(owner, lifeTime, endAction));
            startAction();
        }
    }

    public void Del(int index)
    {
        if (!m_Dic_Buff.ContainsKey(index)) return;
        
        if (m_Dic_Effect.ContainsKey(index))
        {
            if (m_Dic_Effect[index] != null)
                Destroy(m_Dic_Effect[index]);
            m_Dic_Effect.Remove(index);
        }
        
        var action = m_Dic_Buff[index].onEnd;
        m_Dic_Buff.Remove(index);
        action?.Invoke();
    }
    
    public void DelAll()
    {
        foreach (var key in m_Dic_Buff.Keys.ToList())
            Del(key);
    }
    
    public List<int> GetBuffAll()
    {
        return m_Dic_Buff.Keys.ToList();
    }

    private void AttachEffect(int index)
    {
        var buffInfo = DataTableMgr.instance.GetData<BuffInfo>(eDataTableType.BUFF_INFO, index);

        if (buffInfo.m_EffectName.ToLower() == "none")
            return;
        
        Addressables.LoadAssetAsync<GameObject>(buffInfo.m_EffectName).Completed 
            += delegate(AsyncOperationHandle<GameObject> handle)
            {
                if (handle.IsDone)
                {
                    if (!m_Dic_Effect.ContainsKey(index))
                        m_Dic_Effect.Add(index, Instantiate(handle.Result, gameObject.transform.position,
                            gameObject.transform.rotation,
                            gameObject.transform));
                }
            };
    }
}

 

간-_-단

 

728x90

댓글