跳至正文
版本:最新版 - a1.156.0 ⚖️

类指南

关于类你需要了解的一切

nanos world 中的所有实体都由一个类来表示。在 Lua 中,类由表表示。这意味着与实体(Player、Character、Prop 等)的所有交互都是通过遵循 OOP(面向对象程序设计模式)的类/表方法进行的。本页面将对此进行详细解释。

提示

In nanos world we have 4 types of Classes (or structures): Classes, Static Classes, Structs and Utility Classes.

类​

如果你阅读过我们的快速开始指南,你会注意到我们生成实体的格式如下:

Server/Index.lua
-- Spawning an entity with its Constructor (location, rotation and mesh)
local my_prop = Prop(Vector(0, 0, 100), Rotator(), "nanos-world::SM_Cube")

-- Interacting with the entity with its methods
my_prop:SetLocation(Vector(100, 0, 100))
提示

对 实体 / 已生成对象 的 方法 访问是通过 : 实现的。

这就是 OOP 的工作原理!你创建对象,并在该对象上调用函数或捕获事件。与其他拥有大量全局函数和事件来与实体交互的脚本游戏不同,nanos world 脚本是对现代程序设计的一种现代实现方式。

基类​

Under the hood, nanos world Classes follow an Inheritance Pattern, which means we have base parent classes, and their children which "inherit" all functions, events and properties from them. For example, all Classes which exist physically in the world (such as Character and Prop) are Base Actor, so it is possible to call the function :SetLocation() on them.

信息

The Base Entity is the base of all Classes, including the ones which are not in the world (such as Player, WebUI or Database). It contains the methods shared by every Class (like Subscribe, SetValue and Destroy) and the Static Methods to retrieve spawned entities (like GetAll, GetPairs and GetByIndex).

The Base Actor is the base of all Classes which exist in the world, and contains the methods to move, rotate, attach and change the visuals of them.

生成实体​

在 nanos world 中生成实体非常简单直接,假设我们要生成一个 Character:

Server/Index.lua
local my_character = Character(Vector(0, 0, 100), Rotator(), "nanos-world::SK_Male")
提示

每个类都将包含它自己的构造函数、属性、方法和事件。

请在侧边栏的 SCRIPTING REFERENCE → Classes 项中查看 nanos world 提供的所有类。

信息

请记住,某些类只能在服务器生成,而另一些类只能在客户端生成。

销毁实体​

除了 Player 之外,所有类都允许你使用 :Destroy() 方法来销毁它们:

Server/Index.lua
my_character:Destroy()
信息

销毁实体将触发 Destroy 事件,并且还会自动分离所有通过 :AttachTo()¹ 附加到它的实体。

¹如果你在附加实体时将 lifespan_when_detached 参数设置为了 -1 以外的值,那么所有附加的实体也将会被销毁 😉。

静态类​

nanos world 中的静态类是无法被生成的类。相反,你可以直接使用 . 来调用它的方法。

例如,如果你想与太阳/天空/天气进行交互,你将需要 Sky 静态类:

Client/Index.lua
-- 将时间设置为上午 9:25
Sky.SetTimeOfDay(9, 25)
提示

对静态类 / 静态方法的访问是通过 . 实现的。

Structs & Utility Classes​

Besides Classes and Static Classes, we have the Structs and the Utility Classes! Structs are the data types used everywhere in the API, such as Vector, Rotator and Color. Utility Classes are libraries with helper functions, such as JSON and NanosMath.

提示

所有工具类均已在 https://github.com/nanos-world/nanos-world-lua-lib 开源。欢迎随时推送合并请求并提出修改建议!