I have this simple data loading script, but for some reason the script halts at the moment of setting value to an integer. It won’t throw any error or anything, it just stops. I know this because I get nothing in the output, and the code after plrCredits.Value = Data["Credits"] or 0 wont execute - > value “Tokens” is never created.
I should also mention that I have studio API acces turned on, and when I comment out plrCredits.Value = Data["Credits"] or 0 then value “Tokens” is created but script gets stuck again on plrTokens.Value = Data["Tokens"] or 50
my script:
local players = game:GetService("Players")
local replicated = game:GetService("ReplicatedStorage")
local DataStoreService = game:GetService("DataStoreService")
local playerData = DataStoreService:GetDataStore("PlayerData")
players.PlayerAdded:Connect(function(player)
local succes, errorMessage = pcall(function()
local playerID = player.UserId
local key = "P_" .. playerID
local Data = nil
local plrFolder = Instance.new("Folder")
plrFolder.Name = player.Name
plrFolder.Parent = replicated.UserData
local succes, error = pcall(function()
local Data = playerData:GetAsync(key)
end)
local plrCredits = Instance.new("IntValue")
plrCredits.Name = "Credits"
plrCredits.Parent = plrFolder
plrCredits.Value = Data["Credits"] or 0
local plrTokens = Instance.new("IntValue")
plrTokens.Name = "Tokens"
plrTokens.Parent = plrFolder
plrTokens.Value = Data["Tokens"] or 50
end)
end)
The issue is when you say local Data = ... in the second pcall, the variable is lost when the pcall ends, because it is locally inside the pcall, so no other code can access it. Instead, use this:
local succes, errorMessage = pcall(function()
local playerID = player.UserId
local key = "P_" .. playerID
local Data
local plrFolder = Instance.new("Folder")
plrFolder.Name = player.Name
plrFolder.Parent = replicated.UserData
local succes, error = pcall(function()
Data = playerData:GetAsync(key)
end)