My script is supposed to search a folder in each player called “ToolsFolder” when they leave the game and save any string value it can find, however when I join the game, one value loads each time and it is the same value each time. I think the problem is occurring on the loading function, but I could be wrong (Other scripts in the game are transferring more string values into the folder).
Here is the script:
local DataStoreService = game:GetService("DataStoreService")
local StringDataStore = DataStoreService:GetDataStore("StringDataStore")
local Players = game:GetService("Players")
Players.PlayerAdded:Connect(function(player)
local ToolsFolder = Instance.new("Folder")
ToolsFolder.Name = 'ToolsFolder'
ToolsFolder.Parent = player
local ConvertedFolder = Instance.new("Folder")
ConvertedFolder.Name = 'ConvertedFolder'
ConvertedFolder.Parent = player
local UnusedToolsFolder = Instance.new("Folder")
UnusedToolsFolder.Name = 'UnusedToolsFolder'
UnusedToolsFolder.Parent = player
-- Load the string values from the DataStore to the player's ToolsFolder
local success, data = pcall(function()
return StringDataStore:GetAsync("playerData_" .. player.UserId)
end)
if success then
if data ~= nil then
for name, value in pairs(data) do
local stringValue = Instance.new("StringValue")
stringValue.Name = name
stringValue.Value = value
stringValue.Parent = ToolsFolder
print("Successfully Loaded Player Data: "..name)
end
else
local defaultStringValue = Instance.new("StringValue")
defaultStringValue.Name = "Default Mace"
defaultStringValue.Value = "000000"
defaultStringValue.Parent = ToolsFolder
print("Default Mace Granted to Player: "..player.Name)
end
else
print("Error loading player data: " .. data)
end
end)
Players.PlayerRemoving:Connect(function(player)
-- Save the string values from the player's ToolsFolder to the DataStore with unique keys
for _, child in ipairs(player.ToolsFolder:GetChildren()) do
if child:IsA("StringValue") then
print(child.Name)
local key = "playerData_" .. player.UserId .. "_" .. child.Name
local success, data = pcall(function()
return StringDataStore:GetAsync(key)
end)
if success then
--print(child.Name.."1")
if data then
-- print(child.Name.."2")
local newValue = child.Value
local success, errorMessage = pcall(function()
StringDataStore:SetAsync(key, newValue)
print("Successfully Saved Player Data: ".. child.Name)
end)
if not success then
warn("Failed to save player data: " .. errorMessage)
end
end
else
warn("Failed to get player data from the datastore: " .. data)
end
end
end
end)