Hello,
i want to make a script which makes, that all players have the same leaderstats.
This is my code:
hostplr = nil
_G.mainplr = nil
game.Players.PlayerAdded:Connect(function(plr)
for i, player in pairs(game.Players:GetPlayers()) do
if player:WaitForChild("savestats"):WaitForChild("LobbyRole").Value == "host" then
_G.mainplr = player
else
if player:WaitForChild("savestats"):WaitForChild("LobbyRole").Value == "member" then
player:WaitForChild("leaderstats").MoneyOnHand.Value = _G.mainplr.leaderstats.MoneyOnHand.Value
end
end
end
end)
It works, but when a normal player (not the host) loads in before the host, it doesnât work anymore.
I hope someone can help me
~ maini
hostplr = nil
_G.mainplr = nil
function Check(player)
if player:WaitForChild("savestats"):WaitForChild("LobbyRole").Value == "host" then
_G.mainplr = player
else
if _G.mainplr ~= nil then
if player:WaitForChild("savestats"):WaitForChild("LobbyRole").Value == "member" then
player:WaitForChild("leaderstats").MoneyOnHand.Value = _G.mainplr.leaderstats.MoneyOnHand.Value
end
end
end
end
for i,v in pairs(game.Players:GetPlayers()) do
Check(v)
end
game.Players.PlayerAdded:Connect(Check)
Because you are using .PlayerAdded, if the game hasnât loaded or the host is not in the game yet the stat _G.mainplr is never set.
What you should do instead is account for this issue and load when the data is present:
hostplr = nil
_G.mainplr = nil
function LoadData(player)
if player:WaitForChild("savestats"):WaitForChild("LobbyRole").Value == "host" then
_G.mainplr = player
for _, n_player in ipairs(game.Players:GetPlayers()) do
if n_player == player then return end
LoadData(n_player)
end
else
if _G.mainplr ~= nil then
if player:WaitForChild("savestats"):WaitForChild("LobbyRole").Value == "member" then
player:WaitForChild("leaderstats").MoneyOnHand.Value = _G.mainplr.leaderstats.MoneyOnHand.Value
end
end
end
end
game.Players.PlayerAdded:Connect(LoadData)
-- Load previous players
for _, n_player in ipairs(game.Players:GetPlayers()) do
LoadData(n_player)
end
This way you can achieve it, whilst not having the issue of people loading previously.
I usually use a dictionary to store the stats, way more reliable then the leaderstats board and its also more secure - additionally, makes it easier on memory also.