日拱一卒,功不唐捐!Cnblog Labs. �|

畅知

园龄:1年4个月粉丝:68关注:22

Unity热更学习--Lua脚本使用C#中的事件、委托和协程

[14]lua调用使用C#中的事件和委托

C#脚本:继续在Student类中声明

//声明委托和事件
public UnityAction dele;
public event UnityAction eventAction;
public void DoDele()
{
if (dele != null)
dele();
}
public void DoEvent()
{
if (eventAction != null)
eventAction();
}
public void ClearEvent()
{
eventAction = null;
}

lua中进行调用:

--使用委托
function testFun()
print("我在委托中执行 testFun")
end
--第一次委托添加函数时候要直接赋值
student.dele = testFun
student.dele = student.dele + function()
print("我是匿名函数哈哈哈")
end
--不可以直接执行委托 student。dele()
student:DoDele()
--取出函数
student.dele = student.dele - testFun
print("减去TestFun函数")
student:DoDele()
--清空委托中的函数
student.dele = nil
--使用事件
function testFun1()
print("我在事件中执行 testFun1")
end
function testFun2()
print("我在事件中执行 testFun2")
end
student.eventAction = student.eventAction + testFun2
student.eventAction = student.eventAction + testFun1
--触发事件
student:DoEvent()
--从事件中移除函数
student.eventAction = student.eventAction - testFun2
print("再次触发事件")
student:DoEvent()
--不可以直接移除事件
print("事件清除")
student:ClearEvent()

[15]lua调用使用Unity中的协程

----使用C#中的协程
--声明一个协程类型
local Timer = nil
function Counter()
local t = 0
while true do
print(t)
WaitForSeconds(1)
t = t + 1
if t > 60 then
StopTimer()
break
end
end
end
--开启计时器
function StartTimer()
Timer = StartCoroutine(Counter)
end
--停止协程
function StopTimer()
StopCoroutine(Timer)
Timer = nil
end
--调用函数开启计时器
StartTimer()

注意在lua调用入口进行LuaCoroutine注册

image-20240525162235614

本文作者:畅知

本文链接:https://www.cnblogs.com/TonyCode/p/18212582

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   畅知  阅读(115)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起