Unity 内部计时器

封装一个unity计时器及计时完毕回调方法。

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

public class TimingMachinesMgr
{
    private static InternalBehaviour m_IB;

	static TimingMachinesMgr()
	{
		GameObject go = new GameObject("TimingMachinesMgr");
		GameObject.DontDestroyOnLoad(go);
		m_IB = go.AddComponent<InternalBehaviour> ();
	}

	//等待计时
	static public Coroutine WaitTime(float time,UnityAction callback)
	{
		return m_IB.StartCoroutine(Coroutine(time,callback));
	}
	
	//取消等待
	static public void CancelWait(ref Coroutine coroutine)
	{
		if (coroutine != null) {
            Debug.LogError("停止计时器!!!");
			m_IB.StopCoroutine(coroutine);
			coroutine = null;
		}
	}

	static IEnumerator Coroutine(float time, UnityAction callback) {
		yield return new WaitForSeconds (time);
		if (callback != null) {
			callback();
		}
	}
	
	//内部类
    class InternalBehaviour : MonoBehaviour{}
}

调用:

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

public class testtimeerrr : MonoBehaviour
{
    Coroutine coroutine;
    // Start is called before the first frame update
    void Start()
    {
        coroutine = TimingMachinesMgr.WaitTime(5.0f,delegate{
            Debug.LogError("回调方法!!!");
        });
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space)){
            TimingMachinesMgr.CancelWait(ref coroutine);
        }
    }
}

还有一个作者写的超级好,可以参考:【CFramework】Unity定时器Timer封装C#_cchoop的博客-CSDN博客_unity使用 c#定时器

猜你喜欢

转载自blog.csdn.net/ThreePointsHeat/article/details/128239332
今日推荐