Zombie-ish clone game #2

I recommend that you quickly read my first post about this: Zombie-ish clone game

So, the code works and everything but when I leave or reset the clone doesn’t get destroyed?

Code:

game.Players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(char)
		local clone = game.ServerStorage.Dummy:Clone()
		clone.Name = plr.Name.."'s Clone"
		clone.Parent = game.Workspace
		repeat wait()
			clone.Humanoid:MoveTo(char:WaitForChild("HumanoidRootPart").Position)
		until game.Players.PlayerRemoving:Connect(function(plr)
			if game.Workspace:FindFirstChild(plr.Name.."'s Clone") then
				game.Workspace[plr.Name.."'s Clone"]:Destroy()
			end
		end)
	end)
end)

Maybe add a line like

game.Players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(char)
		local clone = game.ServerStorage.Dummy:Clone()
		clone.Name = plr.Name.."'s Clone"
		clone.Parent = game.Workspace
        plr.Character.Humanoid.Died:Connect(function()
            clone:Destroy()
        end)
		repeat wait()
			clone.Humanoid:MoveTo(char:WaitForChild("HumanoidRootPart").Position)
		until game.Players.PlayerRemoving:Connect(function(plr)
			if game.Workspace:FindFirstChild(plr.Name.."'s Clone") then
				game.Workspace[plr.Name.."'s Clone"]:Destroy()
			end
		end)
	end)
end)
1 Like
local players = game:GetService("Players")
local serverStorage = game:GetService("ServerStorage")
local dummy = serverStorage:WaitForChild("Dummy")

players.PlayerAdded:Connect(function(plr)
	plr.CharacterAdded:Connect(function(char)
		local clone = dummy:Clone()
		clone.Name = plr.Name.."'s Clone"
		clone.Parent = workspace
		local hum = char:WaitForChild("Humanoid")
		hum.Died:Connect(function()
			clone:Destroy()
		end)
		repeat wait()
			clone.Humanoid:MoveTo(char:WaitForChild("HumanoidRootPart").Position)
		until players.PlayerRemoving:Connect(function(plr)
			if workspace:FindFirstChild(plr.Name.."'s Clone") then
				workspace:FindFirstChild(plr.Name.."'s Clone"):Destroy()
			end
		end)
	end)
end)