Unity热更学习--Lua脚本使用C#中的事件、委托和协程
  1wMBnbixARwC 2024年08月06日 50 0

[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

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

上一篇: HITSC 1 下一篇: 游戏中的角色运动问题
  1. 分享:
最后一次编辑于 2024年08月06日 0

暂无评论

推荐阅读
  1wMBnbixARwC   2024年08月07日   63   0   0 游戏开发
  NiD7Hlfm86HK   2024年08月07日   58   0   0 游戏开发
  vWa2lMmTbsfJ   2024年08月07日   103   0   0 游戏开发
  PfEVswrG0sbF   2024年08月07日   53   0   0 游戏开发
  1wMBnbixARwC   2024年08月07日   66   0   0 游戏开发
1wMBnbixARwC