for some reason whenever the player exits the game i get an error saying “Unable to cast array” as an errormessage the leaderstats are already defined inside serverscriptservice
local DSS = game:GetService(“DataStoreService”)
local DataStore = DSS:GetDataStore(“LeaderstatsDataStoreTest1”)
local players = game:GetService(“Players”)
game.Players.PlayerAdded:Connect(function(player)
local Coins = player:WaitForChild(“leaderstats”).Coins
local Gems = player:WaitForChild(“leaderstats”).Gems
local data
local success, errormessage = pcall(function()
DataStore:GetAsync(player.UserId, Coins.Value, Gems.Value)
end)
if success then
Coins.Value = data
print("Data SuccessFully Loaded")
else
print("Data either does not exist or there was an error when loading data")
warn(errormessage)
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local Coins = player.leaderstats.Coins
local Gems = player.leaderstats.Gems
local success, errormessage = pcall(function()
DataStore:SetAsync(player.UserId, Coins.Value, Gems.Value)
end)
if success then
print(“Data Successfully Saved!”)
else
print(“There was an error when saving data”)
warn(errormessage)
end
end)
You’re using DataStore incorrectly. There’s a few errors.
Change SetAsync to the following. You can only pass one variable to SetAsync, so pass a table. DataStore:SetAsync(player.UserId, {Coins = Coins.Value, Gems = Gems.Value})
Then you need to change GetAsync too, it’s fetching the above table and needs to be stored into your data variable: data = DataStore:GetAsync(player.UserId)
And now you need to access the data stored inside that table: Coins.Value = data.Coins
Try this. I assume you have code elsewhere that is handling creation of the leaderstats folder and the Coins and Gems IntValues?
local DSS = game:GetService("DataStoreService")
local DataStore = DSS:GetDataStore("LeaderstatsDataStoreTest1")
local Players = game:GetService("Players")
game.Players.PlayerAdded:Connect(function(player)
local Coins = player:WaitForChild("leaderstats").Coins
local Gems = player:WaitForChild("leaderstats").Gems
local success, data = pcall(DataStore.GetAsync, DataStore, player.UserId)
if success then
Gems.Value = data.Gems
Coins.Value = data.Coins
print("Data loaded")
else
print("Error: ", data)
end
end)
game.Players.PlayerRemoving:Connect(function(player)
local data = {
Gems = player.leaderstats.Gems.Value,
Coins = player.leaderstats.Coins.Value
}
local success, error = pcall(DataStore.SetAsync, DataStore, player.UserId, data)
if success then
print("Data Successfully Saved!")
else
print("Error: ", error)
end
end)