Hello, I need help saving car names in strings but in a table like shown in the picture below.
I have a folder called Player_Cars / Car folder and in there cars get put in when they buy them but when the player leaves they won’t get loaded in
My code doesn’t work and I’m not sure why. I get no error messages.
local DataStoreService = game:GetService("DataStoreService")
local playerData = DataStoreService:GetDataStore("PlayerData")
local function onPlayerJoin(player) -- Runs when players join
local carFolder = Instance.new("Folder")
carFolder.Parent = player
carFolder.Name = "Player_Cars"
local ownedCars
local playerUserId = "Player_" .. player.UserId --Gets player ID
local data = playerData:GetAsync(playerUserId) --Checks if player has stored data
if data then
-- Data exists for this player
ownedCars = data.ownedCars
if ownedCars ~= nil then
for i, v in pairs(ownedCars) do
local carClone = game.ReplicatedStorage.Cars[i]:Clone()
carClone.Parent = player.Player_Cars
end
end
else
-- Data store is working, but no current data for this player
ownedCars = nil
end
end
local function saveCars(player)
local playerCars = {}
for i, v in pairs(player.Player_Cars:GetChildren()) do
table.insert(playerCars, v.Name)
end
return playerCars
end
local function onPlayerExit(player) --Runs when players exit
local ownedCars = saveCars(player)
local success, err = pcall(function()
local playerUserId = "Player_" .. player.UserId
playerData:SetAsync(playerUserId, ownedCars) --Saves player data
end)
if not success then
warn('Could not save data!')
end
end
game.Players.PlayerAdded:Connect(onPlayerJoin)
game.Players.PlayerRemoving:Connect(onPlayerExit)