What can be changed, upgraded, added, and what are some things that can make this script more efficient?
CODE
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local PlayerDataStore = DataStoreService:GetDataStore("PlayerData")
local defaultData = {
Level = 1;
XP = 0;
MaxXP = 100;
}
Players.PlayerAdded:Connect(function(player)
local data = nil
local success, err = pcall(function()
data = PlayerDataStore:GetAsync(player.UserId.."-data")
end)
if success then
local level = player:WaitForChild("Data"):WaitForChild("Level")
local xp = level:WaitForChild("XP")
local maxXP = level:WaitForChild("MaxXP")
if data and data ~= defaultData then
print(player.Name.. " has data! Loading data...")
level.Value = data.Level
maxXP.Value = data.MaxXP
xp.Value = data.XP
else
print(player.Name.. " is a new player! Creating new data...")
level.Value = defaultData.Level
maxXP.Value = defaultData.MaxXP
xp.Value = defaultData.XP
end
else
warn("Unable to grab ".. player.Name.."'s data!")
warn("Error:", err)
end
end)
Players.PlayerRemoving:Connect(function(player)
local level = player:WaitForChild("Data"):WaitForChild("Level")
local xp = level:WaitForChild("XP")
local maxXP = level:WaitForChild("MaxXP")
local data = {
Level = level.Value;
XP = xp.Value;
MaxXP = maxXP.Value;
}
local success, err = pcall(function()
PlayerDataStore:UpdateAsync(player.UserId.."-data", function()
return data
end)
end)
if success then
print(player.Name.. "'s data was saved successfully!")
else
warn("Unable to save ".. player.Name.."'s data!")
warn("Error:", err)
end
end)
My main issue with this script is how I use UpdateAsync()
how can I make the saving code better, because right now it just behaves the same as :SetAsync()
.