Skip to content

ModuleScript

概览

字段
KindUnit · 单位 Unit
Realmcommon

继承关系

  • Unit(4 属性 / 25 函数 / 6 事件)

继承成员

2 个来源 / 5 属性 / 25 函数 / 6 事件

ModuleScript 是可被其他脚本 require 的模块脚本 Unit,继承 BaseScript 的 SourceCode 字段,用于沉淀可复用 Lua 逻辑。

适用场景

当多段 ScriptLocalScript 需要复用同一组函数、常量或配置表时,可把公共逻辑放入 ModuleScript,再由调用方脚本 require。

使用要点

通过 game:CreateUnit("ModuleScript", config) 创建实例,设置 Name 与 SourceCode 后挂到 World 或约定目录。ModuleScript 自身没有额外公开函数,脚本内容字段来自 BaseScript

代码示例

创建 ModuleScript 并写入模块代码

lua
-- @runtime client
local World = game:GetService('World')

local moduleScript = game:CreateUnit('ModuleScript', {
    Name = 'SharedLogic',
    SourceCode = 'return { version = 1 }',
})
moduleScript.Parent = World
print('模块脚本源码:', moduleScript.SourceCode)

关联类型