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

实体值

如何将数据存储在可从任何位置访问的实体中

Any Base Entity can store custom values, readable from any Package and optionally synchronized with Clients. Global values can also be stored on the Server and Client Static Classes using the same methods.

SetValue​

:SetValue() stores a value on the entity. On the Server, pass sync_on_clients as true to synchronize it with all clients, including players who join later:

Server/Index.lua
-- Sets a synchronized 'score' value
my_player:SetValue("score", 100, true)

Values are serialized when set: any type is accepted except functions, Lua references are not kept and tables are copied into internal memory. Changing a table after setting it will not affect the stored value, call SetValue() again to update it.

提示

Every change of a synchronized value is sent to all clients. For values changing very often (e.g. every Tick), prefer Remote Events with Reliability.Unreliable.

GetValue​

:GetValue() returns a value, or fallback if the key doesn't exist. Synchronized values can be read on the Client too:

-- Gets 'score' value, or 0 if not set
local score = my_player:GetValue("score", 0)
提示

请注意,存储实体本身并不会因为实体被销毁而使值置空,因此,在检索实体后,最好使用 :IsValid() 来校验。

To list all keys set in an entity, use :GetAllValuesKeys().

Global Values​

Server and Client also have SetValue() and GetValue(), to store values globally instead of on an entity. Server.SetValue() accepts sync_on_clients as well, readable with Client.GetValue(), while Client.SetValue() values only exist on that client:

Server/Index.lua
-- Sets a global synchronized value, readable with Client.GetValue
Server.SetValue("round_number", 1, true)

Listening to Value Changes​

The ValueChange event is triggered whenever a value changes, also on clients for synchronized values. Server and Client have their own ValueChange event for global values.

Client/Index.lua
Player.Subscribe("ValueChange", function(player, key, value)
if (key == "score") then
Console.Log("%s now has %d points!", player:GetName(), value)
end
end)