创造你的世界
脚本编写

UnityEvent

4min
unity提供了unityevents,使用户更容易使用c#事件和委托。 unityevents是一种在满足特定条件时从不同对象传递参数或传递消息的方式。 要在zepetoscript中使用unityevent,您需要按照以下格式声明它。 首先,添加如下的导入命令以使用unityevent类。 typescript import { unityevent } from 'unityengine events'; 查看unityevent的示例耦合代码。 event import { zepetoscriptbehaviour } from 'zepeto script'; import { unityevent } from 'unityengine events'; import { button } from 'unityengine ui'; export default class event extends zepetoscriptbehaviour { public btn button; private mevent unityevent; start() { // 创建unityevent的新实例并将其分配给mevent。 this mevent = new unityevent(); // 向mevent添加一个新监听器。当调用mevent时,此监听器执行ping方法。 this mevent addlistener(() => this ping()); // 检查按钮是否被点击且mevent不为null。 this btn onclick addlistener(() => { if (this mevent != null) { // 如果上述条件为真,则调用mevent。 this mevent invoke(); } }); } ping() { console log('ping'); } } 脚本描述 在上面的示例中,每次按下按钮时,都会调用名为‘mevent’的unityevent,并在调用‘mevent’时执行‘ping’方法。 因此,每次按下按钮时,控制台都会打印一条消息'ping'。 如果您要连接的事件具有参数,则需要添加如下所示的 unityevent 导入命令。 typescript import { unityevent$1 } from 'unityengine events'; 👍 提示 unityevent$1 是 unityevent 的通用版本 例如,如果您想创建一个接受整数值的事件,可以使用 unityevent$1\<int> 请注意,unityevent$1 的参数类型遵循 c# 使用带参数的 unityevent$1 的示例代码如下。 event import { zepetoscriptbehaviour } from 'zepeto script'; import { unityevent$1 } from 'unityengine events'; import { input } from 'unityengine'; export default class event extends zepetoscriptbehaviour { private meventint unityevent$1\<int>; private countnum number; start() { this meventint = new unityevent$1\<int>(); this meventint addlistener(num => this count(num)); this countnum = 0; } update() { if ((input anykeydown) && (this meventint != null)) { this meventint invoke(this countnum); ++this countnum; if (this countnum > 100) { this countnum = 0; } } } count(num) { console log(`count ${num}`); } } 您可以通过点击下面的链接了解更多关于 unityevents 的信息。 📘 unityevents https //docs unity3d com/kr/530/scriptreference/events unityevent html https //docs unity3d com/kr/530/scriptreference/events unityevent html