Unity encapsulates the delay call timer

Time:2020-11-23

This paper shares the specific code of unity encapsulation delay call timer for your reference, the specific content is as follows

Encapsulates a delay call timer class

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

public class WaitTimeManager 
{
 private static TaskBehaviour m_Task;
 static WaitTimeManager()
 {
 GameObject go = new GameObject("#WaitTimeManager#");
 GameObject.DontDestroyOnLoad(go);
 m_Task = go.AddComponent<TaskBehaviour> ();
 }

 //Waiting
 static public Coroutine WaitTime(float time,UnityAction callback)
 {
 return m_Task.StartCoroutine(Coroutine(time,callback));
 }
 
 //Cancel waiting
 static public void CancelWait(ref Coroutine coroutine)
 {
 if (coroutine != null) {
 m_Task.StopCoroutine(coroutine);
 coroutine = null;
 }
 }

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

test

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

public class Script_04_15 : MonoBehaviour {

 void Start () {
 //Turn on the timer
 Coroutine coroutine = WaitTimeManager.WaitTime(5f, delegate {
 Debug.LogFormat ("call back after 5 seconds");
 });

 //Cancel it while waiting
 //WaitTimeManager.CancelWait (ref coroutine);
 }
}

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.

Recommended Today

Talking about Java collection

preface Most programming languages provide array to save objects, and array is one of the most important data structures. However, the length of the array has been defined during initialization, which is immutable and troublesome to use. Therefore, Java inJDK 1.2The collection framework is added to the version to save and manipulate objects. The container […]