跳到主要内容

空白脚本(Blank Scripts)

空白脚本(Blank Scripts)用于把可复用逻辑拆分为小模块,并在多个脚本间共享。

非常适合数学工具、几何函数、颜色工具等辅助逻辑。

创建空白脚本​

创建新脚本 并选择 空白(Blank) 类型。

--- Example helper function.
local function add(a: number, b: number): number
return a + b
end

-- Return the functions you'd like to use in another script
return {
add = add,
}

用法(Usage):

local MyUtil = require("MyUtil")

local result = MyUtil.add(2, 3)
print(result) -- 5

带自定义类型的空白脚本​

在空白脚本中定义的自定义类型(Custom Types)可在引用脚本中直接使用。

--- Defines the return type for this util.
--- The type is automatically available when you require the script.
export type AdditionResult = {
exampleValue: number,
someString: string
}

--- Example helper function.
local function add(a: number, b: number): AdditionResult
return {
exampleValue = a + b,
someString = "4 out of 5 dentists recommend Rive"
}
end

return {
add = add,
}

用法(Usage):

-- With type annotation
local result: AdditionResult = MyUtil.add(2, 3)

引用文件夹中的脚本(Requiring scripts in folders)​

把脚本放进资源面板的文件夹后,文件夹路径会成为脚本的命名空间。选中脚本,可以在检查器中看到它的 命名空间(Namespace)。

脚本的完整模块名是命名空间和名称用 / 连接。require 时使用完整模块名。例如,Utils 文件夹里的 Math 文件夹中、名为 Vector 的脚本这样引用:

local Vector = require("Utils/Math/Vector")

不在文件夹里的脚本没有命名空间,只按名称引用。把脚本移到别的文件夹,或重命名它所在的文件夹,都会改变它的模块名。

看完还有疑问?进群交流下!
与众多 Rive 创作者、开发者一起交流探讨与答疑解惑。
加入交流群