unity中Invoke()使用

11 篇文章 0 订阅

Invoke(“方法名”,间隔时间)//每隔多少时间执行一次某方法

InvokeRepeating("printMessage",2f,3f);//2s后调用一次每隔3三调用一次

所以说写在void start()函数里的InvokeRepeating("printMessage",2f,3f);方法和写在void update()的Invoke()方法效果可能一样

UnityInvoke函数可以在指定的时间后调用一个指定的函数。Invoke函数的语法如下: ```csharp public void Invoke(string methodName, float time); public void InvokeRepeating(string methodName, float time, float repeatRate); ``` 其,methodName参数表示要调用的函数名,time参数表示延时时间(以秒为单位),repeatRate参数表示重复调用时间间隔(仅在InvokeRepeating函数使用)。 以下是一个使用Invoke函数实现延时调用函数的示例代码: ```csharp using UnityEngine; public class InvokeExample : MonoBehaviour { void Start() { Invoke("DelayedFunction", 2.0f); } void DelayedFunction() { Debug.Log("Delayed function called after 2 seconds"); } } ``` 在上述示例代码,Start()函数调用了Invoke函数,并指定了要调用的函数名(DelayedFunction)和延时时间(2.0f)。在指定时间结束后,会调用DelayedFunction函数,并输出一条日志信息。 需要注意的是,Invoke函数只能调用无参函数,并且不能传递参数。如果需要传递参数,可以使用Lambda表达式或定义一个新的带参函数来实现。例如: ```csharp using UnityEngine; public class InvokeExample : MonoBehaviour { void Start() { int delayTime = 2; Invoke("DelayedFunction", delayTime); Invoke(() => DelayedFunctionWithParam("Hello", 10), 5.0f); } void DelayedFunction() { Debug.Log("Delayed function called after 2 seconds"); } void DelayedFunctionWithParam(string message, int count) { for (int i = 0; i < count; i++) { Debug.Log(message); } } } ``` 在上述示例代码使用Lambda表达式和定义一个新的带参函数来实现传递参数的效果。Lambda表达式包含了要调用的函数和传递的参数,可以方便地实现带参函数的调用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值