How can I edit this script to retrieve the data from datastore and give it to the player? Are there any errors in my code? I’m new to coding so I’m using tutorials to help me learn code.
local DataStoreService = game:GetService("DataStoreService")
local CashDataStore = DataStoreService:GetDataStore("CashDataStore")
function onPlayerEntered(newPlayer)
local success, cashValue = pcall(function()
return CashDataStore:GetAsync(newPlayer.UserId)
end)
if not success then
-- an error occurred while trying to retrieve the value from the DataStore
-- you can log the error message or take some other action here
print("Error retrieving cash value from DataStore: " .. cashValue)
return
end
local stat = newPlayer:FindFirstChild("leaderstats")
if not stat then
stat = Instance.new("IntValue")
stat.Name = "leaderstats"
stat.Parent = newPlayer
end
local cash = stat:FindFirstChild("Cash")
if not cash then
cash = Instance.new("IntValue")
cash.Name = "Cash"
cash.Parent = stat
end
cash.Value = cashValue
end
game.Players.ChildAdded:Connect(onPlayerEntered)
Any help would be greatly appreciated and if possible I would like for you to explain why certain things work. Thank you!!
local DataStoreService = game:GetService("DataStoreService")
local CashDataStore = DataStoreService:GetDataStore("CashDataStore")
game.Players.PlayerAdded:Connect(function(Plr)
-- Stats
local ls = Instance.new("Folder", Plr)
ls.Name = "leaderstats"
local cs = Instance.new("IntValue", ls)
cs.Name = "cash"
--
local Success, Data = pcall(function()
return CashDataStore:GetAsync(Plr.UserId) -- returns Data
end)
if Success then -- If Accessed DataStores
if Data then -- If Data found
cs.Value = Data -- Value is equal to Data
else -- If No Data
cs.Value = 0 -- No Data
end
else -- If Failed to Access DataStores
Plr:Kick("Error in loading data!") -- Kicks Player
end
end)
local CashDataStore = DataStoreService:GetDataStore("CashDataStore")
function onPlayerEntered(newPlayer)
local CashData
local success, fail = pcall(function()
CashData CashDataStore:GetAsync(newPlayer.UserId)
end)
if not success then
-- an error occurred while trying to retrieve the value from the DataStore
-- you can log the error message or take some other action here
print("Error retrieving cash value from DataStore: " .. cashValue)
return
end
local stat = newPlayer:FindFirstChild("leaderstats")
if not stat then
stat = Instance.new("IntValue")
stat.Name = "leaderstats"
stat.Parent = newPlayer
end
local cash = stat:FindFirstChild("Cash")
if not cash then
cash = Instance.new("IntValue")
cash.Name = "Cash"
cash.Parent = stat
end
cash.Value = CashData
end
game.Players.ChildAdded:Connect(onPlayerEntered)