赞
踩
public class Test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
StartCoroutine(DelayExecute());
}
IEnumerator DelayExecute()
{
yield return new WaitForSeconds(2f);
Debug.Log("延迟2秒后执行");
}
}
(1)使用Invoke:
using UnityEngine;
public class Test : MonoBehaviour
{
private void Start()
{
Invoke("DelayedExeCute", 2f); //2秒后执行
}
private void DelayedExeCute()
{
Debug.Log("延迟后,执行!");
}
}
(2)使用InvokeRepeating:
using UnityEngine;
public class Test: MonoBehaviour
{
private void Start()
{
InvokeRepeating("DelayedExeCute", 2f, 2f);//2s后开始执行,并且之后每个2s重复执行一次。
}
private void DelayedExeCute()
{
Debug.Log("延迟后,执行!");
}
}
注意:
可通过以下一些集成好的方法检测或停止Invoke的状态。
IsInvoking(): 判断是否有通过Invoke方式调用的函数,只要有Invoke在运行,就返回true.
IsInvoking(函数名): 指定函数名称,当这个函数正在Invoke的时候返回true
CancelInvoke(函数名): 取消所有Invoke或者对应Invoke
using UnityEngine; public class Test : MonoBehaviour { private float startTime; private float delayTime = 2f; // 延时时间为2秒 private flaot elapsedTime=0; private void Start() { startTime = Time.time;// 记录开始时间 } private void Update() { elapsedTime = Time.time - startTime;// 时间差 if (elapsedTime >= delayTime)// 判断是否达到延时时间 { ExecuteAction();//已经达到,执行延时后的操作 } } private void ExecuteAction() { Debug.Log("开始执行操作"); } }
using UnityEngine; public class Test: MonoBehaviour { private float delayTime = 3f; // 延时时间为3秒 private float elapsedTime=0; private void Update() { elapsedTime += Time.deltaTime; // 累加时间 if (elapsedTime >= delayTime)// 判断是否达到延时时间 { ExecuteAction();//已经达到,执行延时后的操作 } } private void ExecuteAction() { Debug.Log("开始执行操作"); elapsedTime = 0f; //清空重置 } }
using UnityEngine; using DG.Tweening; public class Test: MonoBehaviour { private void Start() { float delayTime = 2f; // 延时2秒后执行回调函数 DOTween.To(() => 0, x => { }, 0, delayTime) .OnComplete(() => { Debug.Log("延时结束!"); }); } }
public class Test: MonoBehaviour { private void Start() { vp_Timer.In(2f, ExecuteMethod);//2秒后调用 vp_Timer.In(2f, ExecuteMethod, 3);//2秒后调用,间隔1秒调用3次 vp_Timer.In(2f, ExecuteMethod,4, 1); //2秒后调用,间隔1秒调用4次 vp_Timer.In(2f, ExecuteMethod, 0, 1);//2秒后调用,间隔1秒调用无限次 vp_Timer.In(1.0f, MethodWithArgument, "CanShuValue");//带参数调用 vp_Timer.In(1.0f, MethodWithArguments,new object[] { "A", 1, 2 }); //带多个参数调用 //vp_Timer.CancelAll(); //取消所有定时器 //vp_Timer.CancelAll("SomeMethod"); //取消定时器 } void ExecuteMethod() { Debug.Log("延迟后,开始执行"); } void MethodWithArgument(object o) { string s = (string)o; Debug.Log("传过来的参数:"+s); } void MethodWithArguments(object o) { object[] arg = (object[])o; Debug.Log("1: " + (string)arg[0]+ ", 2:" + (int)arg[1]+ ", 3:" + (int)arg[2]); } }
这里是井队,天高任鸟飞,海阔凭鱼跃,点个关注不迷路,我们下期再见。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。