Unity事件系统

来源:互联网 发布:工业企业数据库 编辑:程序博客网 时间:2024/05/20 17:59
using System;
using System.Collections.Generic;
using UnityEngine;

public class EventItem
{
    private object parameter;
    private float time;
    private float timer;
    private int count;
    public void Add(EventBindFunction function)
    {
        eventBindFunction += function;
    }
    public void Remove(EventBindFunction function)
    {
        try
        {
            eventBindFunction -= function;
        }
        catch(Exception ex)
        {
            MyDebug.Instance.LogError(ex + ":卸载不存在事件");
        }
    }
    public void Handle()
    {
        if (eventBindFunction != null)
            eventBindFunction(parameter);
    }
}
public class EventManager  {


    private Dictionary<EventType, EventItem> eventDic = new Dictionary<EventType, EventItem>();
    private List<EventItem> eventList = new List<EventItem>();


    private EventManager() { }
    private static EventManager instance;
    public static EventManager Instance
    {
        get
        {
            if (instance == null)
                instance = new EventManager();
            return instance;
        }
    }
    
    public void RegisterEvent(EventType eventType,EventBindFunction function)
    {
        if (eventDic.ContainsKey(eventType))
        {
            eventDic[eventType].Add(function);
        }
        else
        {
            EventItem item = new EventItem();
            eventDic.Add(eventType, item);
        }
    }
    public void UnRegisterEvent(EventType eventType,EventBindFunction function)
    {
        if (eventDic.ContainsKey(eventType))
        {
            EventItem item = eventDic[eventType];
            if (eventList.Contains(item))
                eventList.Remove(item);
        }
        else
        {
            MyDebug.Instance.LogError("卸载不存在事件类型");
        }
    }
    public void FireEvent(EventType eventType,object obj=null)
    {
        if (eventDic.ContainsKey(eventType))
        {
            eventDic[eventType].Handle();
        }
        else
        {
            MyDebug.Instance.LogError("执行不存在事件类型");
        }
    }
}
原创粉丝点击