Help with saving parts to datastore

Hello DevFourm, I am working on a system to save parts and the properties of the parts to a datastore. I have tried everything I know and can’t find out how to do it.

Here is the script I have written so far:

local part = game.Workspace.PlayArea:GetChildren()
local dataStoreService = game:GetService("DataStoreService")
local playerData = dataStoreService:GetDataStore("PlayerParts")
local dataEvent = game.ReplicatedStorage.Data
local httpService = game:GetService("HttpService")


function dataStoreGet(plr)
	print("hi")
	local data = nil

	local complete, errorMsg = pcall(function()
		local dataEncoded = playerData:GetAsync(plr.UserId)
		data = httpService:JSONDecode(dataEncoded)
	end)
	
	if complete and data then
		for i,v in pairs(data) do
			local part = Instance.new("Part")
			part.Parent = game.Workspace.PlayArea
			part.Position = game.Workspace.PartSpawnWS.Position
			part.Color = v.Color
			part.Material = v.Material
		end
	else
		warn("Data Error: "..errorMsg)
	end
	
	print(data)
end

function saveData(plr)
	local parts = game.Workspace.PlayArea:GetChildren()
	
	for i, v in pairs(parts) do
		part[i] = {
			Position = v.Position,
			Color = v.Color,
			Material = v.Material
		}
		
		print(v.Color)
		
		local plrDataString = httpService:JSONEncode(part[i])
		
		local complete, errorMsg = pcall(plr.UserId, plrDataString)
		
		playerData:SetAsync(plrDataString, plr.UserId)

		if complete then
			print("Data Message: Data Has Been Saved")

		else

			print("Data Error: ".. errorMsg)
		end
		
		print(plrDataString)
	end
end


game.Players.PlayerAdded:Connect(function(plr)
	dataStoreGet(plr)
end)
game.Players.PlayerRemoving:Connect(function(plr)
	saveData(plr)
end)

game:BindToClose(function()
	for i,v in pairs(game.Players:GetPlayers()) do
		task.spawn(saveData, v)
	end
end)

Thank you :slight_smile:

Edit: Some things in the script might be unorganized or unnecessary due to me trying to fix the problem! Most of the random print statements are just from debugging.