Entitätswerte
Wie man Daten in allen verfügbaren Entitäten speichert
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:
-- 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)
Be aware that storing entities itself will not nullify the value if the entity is destroyed, so it is a good practice to validate if values with :IsValid() after retrieving them.
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:
-- 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.
Player.Subscribe("ValueChange", function(player, key, value)
if (key == "score") then
Console.Log("%s now has %d points!", player:GetName(), value)
end
end)