using System;
using System.Collections.Generic;
using UnityEngine;
///
/// 延迟几秒执行事件
///
public class WaitCallBack : MonoBehaviour
{
internal float waitTime = 2.0f;
public bool doOnAwake = false;
///
/// 时间到达回调
///
public Action OnCompelete;
///
/// 每帧回调
///
public Action OnWait;
internal static Dictionary waitDic = new Dictionary();
private float m_Time = 0;
private bool start = false;
private Component m_Comp;
private void Awake()
{
if (doOnAwake)
{
Play();
}
}
private void OnDisable()
{
Stop();
}
private void Update()
{
if (start)
{
m_Time += Time.deltaTime;
if (m_Time >= waitTime)
{
Stop();
if (OnCompelete != null)
OnCompelete(m_Comp);
}
if (OnWait != null && start)
OnWait(m_Comp);
}
}
internal void Play()
{
start = true;
}
internal void Restart()
{
m_Time = 0;
Play();
}
internal void Stop()
{
m_Time = 0;
start = false;
}
internal void Pause()
{
start = false;
}
private void OnDestroy()
{
if (waitDic.ContainsKey(gameObject))
{
waitDic.Remove(gameObject);
}
}
internal void AddWaitDic(Component go)
{
m_Comp = go;
waitDic.Add(go.gameObject, this);
}
}
public static class Helper
{
public static void DoWaitStart(this Component go)
{
if (GetWait(go) == null)
return;
GetWait(go).Play();
}
public static void OnWaitCompelete(this Component go, Action func)
{
WaitCallBack wait = GetWait(go);
if (wait == null)
return;
wait.OnCompelete = func;
}
public static void OnWait(this Component go, Action func)
{
WaitCallBack wait = GetWait(go);
if (wait == null)
return;
wait.OnWait = func;
}
public static void DoWaitRestart(this Component go)
{
if (GetWait(go) == null)
return;
GetWait(go).Restart();
}
public static void DoWaitStop(this Component go)
{
if (GetWait(go) == null)
return;
GetWait(go).Stop();
}
public static void DoWaitPause(this Component go)
{
if (GetWait(go) == null)
return;
GetWait(go).Pause();
}
public static WaitCallBack GetWait(Component go)
{
WaitCallBack wait = null;
if (go == null)
return null;
WaitCallBack.waitDic.TryGetValue(go.gameObject, out wait);
if (wait == null)
{
wait = go.GetComponent();
if (wait == null)
{
wait = go.gameObject.AddComponent();
}
wait.AddWaitDic(go);
}
return wait;
}
public static void SetWait(this Component comp, float time)
{
WaitCallBack wait = GetWait(comp);
if (wait != null)
{
wait.waitTime = time;
}
}
}