Tying server sided values to players?

Is there any way of creating values on the server that can be traced to certain players?
basically how do i go about storing player specific values on the server

Im not talking about saving data between sessions, i mean having values that are used by the server, and are accessed often but cannot be read/written by clients

Indeed there is. You can store values in value instances like this:

game.Players.PlayerAdded:Connect(function(plr)
    local GoldAmount = Instance.new("NumberValue")
    GoldAmount.Name = "GoldAmount" .. tostring(plr.UserId) --// Make name unique with player's ID
    GoldAmount.Value = 0
    GoldAmount.Parent = script --// ...or wherever works for your game best
end)

game.Players.PlayerRemoving:Connect(function(plr)
    local Value = script["GoldAmount" .. tostring(plr.UserId)].Value --// Access value with player's ID
    print("Player left with " .. tostring(Value) .. " gold on hand"
end)

OR
You can store values in a table.

local DefaultTable = {Apples = 0,Bananas = 0}
local PlayerData = {}

game.Players.PlayerAdded:Connect(function(plr)
    PlayerData[plr.UserId] = DefaultTable
end)

game.Players.PlayerRemoving:Connect(function(plr)
    PlayerData[plr.UserId] = nil --// Delete the table because since the player left
end)

--// Editing value for first player found with :FindFirstChildOfClass()
task.wait(1.5)
local ID = game.Players:FindFirstChildOfClass("Player").UserId
PlayerData[ID].Apples = 5

Which of the two methods you use depends on what the data is and where all it’s needed (big difference between 1 script vs 26 scripts), but I recommend going for the option with value instances.

1 Like

Thank you, but how does this line,

local Value = script["GoldAmount" .. tostring(plr.UserId)].Value

work?
does it get a number value from two strings, and how?

Yes, that line is getting a NumberValue that’s parented to the script. We construct the NumberValue’s name by combining GoldAmount and tostring(plr.UserId), then use the resulting string in brackets after script to reference the exact NumberValue instance we want. It’s like how we’d do something like Model["Red line"] to reference an instance whose name has spaces in it.

I just realized I screwed up the PlayerRemoving portion of the first method by forgetting to destroy the value object after the player leaves. The code should actually be like this:

game.Players.PlayerRemoving:Connect(function(plr)
    local ValueObject = script["GoldAmount" .. tostring(plr.UserId)] --// Access with player's ID
    print("Player left with " .. tostring(ValueObject.Value) .. " gold on hand"
    ValueObject:Destroy()
end)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.