How to store data in Entities accessible from anywhere
In nanos world it is possible to store data on entities. Those values can be accessed by any Package and also you can determine if the value will be automatically synchronized with the Clients.
In any entity, you can use the method
:SetValue(key, value, sync) to set any kind of value on that entity. Example:
-- Sets a synchronized 'my_value' value
my_player:SetValue("my_value", 100, true)
It is possible to store any kind of value, except
If you pass
sync as true, that value will be automatically synchronized with all clients. Note that
syncis an optional parameter only available on the Server side.
Client.SetValue() and Server.SetValue() won't have the last parameter
sync. As the value will only exist on the side you are setting.
After set, you can access any value from any entity using
:GetValue(key, fallback) on any entity you want. If you set the value to be synchronized on Clients, you will be able to get the values on the Client side as well. You can pass an aditional parameter
fallback which will be returned if the key doesn't exist!
-- Gets 'my_value' value, or returns '0' if no value is set
local my_value = my_player:GetValue("my_value", 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.