Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Error while loading datastore data?

local ds = game:GetService("DataStoreService")
local players = game:GetService("Players")

players.PlayerAdded:connect(function(player)
	local userid = "user_"..player.UserId
	local money_store = ds:GetDataStore("Money")
	local money_stats = player:WaitForChild("leaderstats").Money.Value
	local newmoney = money_store:GetAsync(userid)
	print(newmoney)
	player:WaitForChild("leaderstats").Money.Value = newmoney

end)

players.PlayerRemoving:connect(function(player)
	local userid = "user_"..player.UserId
	local money = ds:GetDataStore("Money")
	local money_stats = player:WaitForChild("leaderstats").Money.Value
	print(money_stats)
	money:SetAsync(userid,money_stats)
end)

Why when loading data I get nil when I use print (newmoney)?

1 comment

0

Are you running this in studio? You'll have to enable studio API functions since it defaults to disallow datastores via studio

1 answer

leaderstats & Money thing doesn't create when a player joins. Yeah so I rewrote it:

local ds = game:GetService("DataStoreService")
local players = game:GetService("Players")

players.PlayerAdded:connect(function(player)
    local userid = "user_"..player.UserId
    local money_store = ds:GetDataStore("Money")
    local leaderstats = instance.new("IntValue", player) -- Create new instance and parent it to player

    leaderstats.Name = "leaderstats" -- Name previous instance leaderstats

    local money_stats = instance.new("IntValue", leaderstats) -- Create new instance and parent it to leaderstats

    money_stats.Name = "Money"  -- Name previous instance Money

    money_stats.Value = money_store:GetAsync(userid) or 0 -- Set money value to datastore or set it to 0

    print(money_stats.Value) -- print money value
end)

players.PlayerRemoving:connect(function(player)
    local userid = "user_"..player.UserId
    local money = ds:GetDataStore("Money")
    local money_stats = player:WaitForChild("leaderstats").Money
    print(money_stats.Value)
    money:SetAsync(userid,money_stats.Value)
end)

1 comment

0

Alas, but it does not work. By the way, in the studio my script does not work, and in the game everything is okay

This discussion is preserved as it was. New answers, comments, and votes are closed.