I’m trying to save the items (parts) inside of a folder in ReplicatedStorage. I don’t know what’s going on with this DataStore because everything looks right. I’ve tried following tutorials, and seeing free models but none seem to work.
Part is cloned to workspace so I can see that it registers
Script:
local DataStoreService = game:GetService("DataStoreService")
local AbilitiesDataStore = DataStoreService:GetDataStore("AbilitiesDataStore")
local AbilitiesFolder = game.ReplicatedStorage:WaitForChild("MatchVariables").MatchEquipment.Abilities
game.Players.PlayerAdded:Connect(function(Player)
pcall(function()
local StoreKey = AbilitiesDataStore:GetAsync(Player.UserId)
if StoreKey then
for i, SaveObject in pairs(StoreKey) do
for i, Ability in pairs(AbilitiesFolder:GetChildren()) do
if Ability then
Ability:Clone().Parent = game.Workspace
end
end
end
end
end)
end)
game.Players.PlayerRemoving:Connect(function(Player)
pcall(function()
local SavingObjects = {}
for i, Object in pairs(AbilitiesFolder:GetChildren()) do
table.insert(SavingObjects, Object.Name)
end
AbilitiesDataStore:SetAsync(Player.UserId, SavingObjects)
end)
end)
local DataStoreService = game:GetService("DataStoreService")
local AbilitiesDataStore = DataStoreService:GetDataStore("AbilitiesDataStore")
local AbilitiesFolder = game.ReplicatedStorage:WaitForChild("MatchVariables").MatchEquipment.Abilities
game.Players.PlayerAdded:Connect(function(Player)
local StoreKey
local success, err = pcall(function() StoreKey=AbilitiesDataStore:GetAsync(Player.UserId) end)
if success and StoreKey then
for _, SaveObject in pairs(StoreKey) do
for _, Ability in pairs(AbilitiesFolder:GetChildren()) do
if SaveObject then Ability:Clone().Parent = game.Workspace end
end
end
end
if not success then warn(err) end
end)
game.Players.PlayerRemoving:Connect(function(Player)
local SavingObjects = {}
for i, Object in pairs(AbilitiesFolder:GetChildren()) do
table.insert(SavingObjects, Object.Name)
end
local success, err = pcall(function() AbilitiesDataStore:SetAsync(Player.UserId, SavingObjects)end)
if not success then warn(err) end
end)
I haven’t tested the code but it should work.
I think the problem you were having comes from this:
for i, SaveObject in pairs(StoreKey) do
for i, Ability in pairs(AbilitiesFolder:GetChildren()) do
if Ability then
Ability:Clone().Parent = game.Workspace
end
end
end
but you should be checking for SaveObject not Ability in the second loop.
Potential Problem: Game is closing before the player removing event can fire.
To solve this simply bind a “save all” to game close, with something like this:
game:BindToClose(function()
for Name, Player in pairs(game.Players:GetPlayers()) do
pcall(function()
local SavingObjects = {}
for i, Object in pairs(AbilitiesFolder:GetChildren()) do
table.insert(SavingObjects, Object.Name)
end
AbilitiesDataStore:SetAsync(Player.UserId, SavingObjects)
end)
end
end)