I cannot get to save data in a roblox game.
local players = game:GetService("Players")
local dss = game:GetService("DataStoreService")
local gameData = dss:GetDataStore("Nara")
players.PlayerAdded:Connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player
local coins = Instance.new("IntValue")
coins.Name = "Coins"
coins.Parent = leaderstats
local success, result = pcall(function()
local r = gameData:GetAsync(player.UserId)["Coins"]
return r
end)
if success then
print("success: " .. result)
coins.Value = result
else
print(result)
end
end)
players.PlayerRemoving:Connect(function(player)
print("player removed")
local key = player.UserId
local data = {
["Coins"] = player:WaitForChild("leaderstats").Coins.Value
}
local success, err = pcall(function()
gameData:SetAsync(key, data)
end)
if success then
print("Data saved successfully")
else
print("Failed to save data with error: ", err)
end
end)
game.ReplicatedStorage.Buy.OnServerInvoke = function(player, item)
if not player:FindFirstChild(item) then
if player.leaderstats.Coins.Value >= game.ReplicatedStorage.Items:WaitForChild(item).cost.Value then
player.leaderstats.Coins.Value = player.leaderstats.Coins.Value - game.ReplicatedStorage.Items:WaitForChild(item).cost.Value
local owned = Instance.new("BoolValue")
owned.Name = item
owned.Parent = player
player.Backpack:ClearAllChildren()
game.ReplicatedStorage.Items:WaitForChild(item):Clone().Parent = player.Backpack
return item
else
return "not enough coins"
end
else
player.Backpack:ClearAllChildren()
game.ReplicatedStorage.Items:WaitForChild(item):Clone().Parent = player.Backpack
return "owned " .. item
end
end
i tried more ways i dont know whats wrong.
I was expecting for the Coins IntValue to be saved then loaded when player joins. I tried everything but didnt get it to work. The value is created and nothing destroyed it. The code gets stuck at pcall for saving, tried to see where using print
. Thanks
Have you enabled studio access? If not, you could read this documentation on how to enable it: https://create.roblox.com/docs/cloud-services/datastores
By default, experiences tested in Studio can't access data stores, so you must first enable them. Accessing data stores in Studio can be dangerous for live experiences because Studio accesses the same data stores as the client application. To avoid overwriting production data, do not enable this setting for live experiences. Instead, enable it for a separate test version of the experience.
To enable Studio access in a published experience:
- Go to Home > Game Settings > Security.
- Enable the Enable Studio Access to API Services toggle.
- Click Save.