I've debugged to see what's happening at a better perspective, and I found that CollectedData appears to be empty, and DataSaved as well. Everything works fine, Loaded is true etcetera.
--###----------[[SERVICES]]----------##--
local DataStoreService = game:GetService("DataStoreService")
local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
--###----------[[VARAIABLES]]----------##--
local MyData1 = DataStoreService:GetDataStore("MyData1")
local Leaderstats = script.leaderstats
--###----------[[FUNCTIONS]]----------##--
local function CollectPlayerData(Player)
local CollectedData = {}
---------------
local DataObjects = Player.leaderstats:GetChildren()
for _, Data in pairs(DataObjects) do
CollectedData[Data.Name] = Data.Value
end
---------------
return CollectedData
end
local function LoadPlayerData(Player)
local DataFolder = Leaderstats:Clone()
DataFolder.Parent = Player
---------------
local DataKey = "Player_"..Player.UserId
local Loaded, DataSaved = pcall(MyData1.GetAsync, MyData1, DataKey)
---------------
if (Loaded and DataSaved) then
---------------
for DataName, Data in pairs(DataSaved) do
local DataObject = DataFolder:FindFirstChild(DataName)
if (DataObject) then
DataObject.Value = Data
end
end
else
MyData1:SetAsync(DataKey, CollectPlayerData(Player))
end
end
local function SavePlayerData(Player)
--if (RunService:IsStudio()) then return end
---------------
local DataKey = "Player_"..Player.UserId
---------------
MyData1:SetAsync(DataKey, CollectPlayerData(Player))
end
--###----------[[SETUP]]----------##--
Players.PlayerAdded:Connect(LoadPlayerData)
Players.PlayerRemoving:Connect(SavePlayerData)

3 comments
Are you trying to do this in studio or in the game? If you're in studio, you have to enable API services on the game.
api services is enabled thats why if (RunService:IsStudio()) then return end is commented
What happens if on line 41, you add
print(Loaded, DataSaved)?