创造你的世界
脚本编写
脚本导入
3分
除了附加到 gameobject,zepetoscript 还可以被其他脚本直接使用。 您可以像使用库或模块一样简单地导入和使用 zepetoscript。在 typescript 语法中,您需要使用相对路径来指向 zepetoscript 文件。 考虑以下情况,如果您想将 extracomponent 导入到 scriptimport 中,您需要使用以下语法。 以下示例是在 scriptimport ts 中声明以调用位于 lib 文件夹中的 extracomponent ts。 typescript import extracomponent from ' /lib/extracomponent'; 👍 提示 在导入另一个 ts 文件时,正确指定路径非常重要。 请熟悉相对路径表示法。 / 表示当前目录。 / 表示父目录,即当前目录上一级的目录。 您可以通过直接引用导入脚本中声明的导出函数和变量来访问它们,如示例所示。 this gameobject addcomponent\<extracomponent>(); const extracomponent = this gameobject getcomponent\<extracomponent>(); // 通过方法调用获取值 const count = extracomponent getcount(); // 通过方法调用设置值 extracomponent setcount(0); // 获取公共属性 const resultstring = extracomponent stringproperty; 以下是显示导入的 typescript 的示例代码。 import { zepetoscriptbehaviour } from 'zepeto script'; import { text } from 'unityengine ui'; // 从路径导入自定义脚本 import extracomponent from ' /lib/extracomponent'; export default class scriptimport extends zepetoscriptbehaviour { public resultui text; private extcomponent extracomponent; start() { // 添加脚本组件 this gameobject addcomponent\<extracomponent>(); this extcomponent = this gameobject getcomponent\<extracomponent>(); } update() { // 通过方法调用获取值 const count = this extcomponent getcount(); if (count > 10) { // 通过方法调用设置值 this extcomponent setcount(0); } // 获取公共属性 const resultstring = this extcomponent stringproperty; // 打印结果 console log(`result ${resultstring}`); this resultui text = resultstring; } } extracomponents 的示例代码。 import { zepetoscriptbehaviour } from 'zepeto script'; export default class extracomponent extends zepetoscriptbehaviour { public stringproperty string; private message string; private count int; start() { this message = "嗨,zepeto!"; this count = 0; } update() { this stringproperty = `${this message} ${this count++}`; } getcount() { return this count; } setcount(newcount int) { this count = newcount; } } 请查看下面的测试代码输出屏幕。