How to not run an event when something is happening

I made a character save system & there’s a slight problem, the function runs when the character is added, but in the script, it replaces your character with another one which the script detects and runs it again, this causes lag and runs it in a loop.

I am trying to get it to work without calling the function when I change the Player.Character in the function.

game.Players.PlayerAdded:Connect(function(Player)
	Player.CharacterAdded:Connect(function()
			repeat wait() until Player.Character
			for i, v in pairs(Player.Character:GetChildren()) do
				if v:IsA("MeshPart") then
					v.BrickColor = BrickColor.new(Player.StatsFolder.SkinColor.Value)
				end
			end

			--// Hair
			local Hair = game.ReplicatedStorage.CharacterCreationFolder.Hairs:FindFirstChild(Player.StatsFolder.Hair.Value):Clone()
			Hair.Parent = Player.Character

			local Gender = game.ReplicatedStorage.CharacterCreationFolder.Genders:FindFirstChild(Player.StatsFolder.Gender.Value):Clone()
			local character = Player.Character

			Gender.Name = Player.Name

			local rootPart = Gender:FindFirstChild("HumanoidRootPart") or Gender:FindFirstChild("LowerTorso")
			local plrRoot = Player.Character:FindFirstChild("HumanoidRootPart") or Player.Character:FindFirstChild("LowerTorso")

			if rootPart and plrRoot then
				rootPart.CFrame = plrRoot.CFrame
			end

			Gender.Parent = workspace
			Player.Character = Gender
			--// Clothing
			Player.Character:WaitForChild("Shirt").ShirtTemplate = tostring(Player.StatsFolder.Shirt.Value)
			Player.Character:WaitForChild("Pants").PantsTemplate = tostring(Player.StatsFolder.Pants.Value)
			--// Name
			Player.Character.Humanoid.DisplayName = tostring(Player.StatsFolder.FirstName.Value.." "..Player.StatsFolder.LastName.Value)
		end)
end)

You should probably use a debounce. It stops the event from running while it is already running.

Apologies for the formatting.

local debounce = false
Player.characterAdded:Connect(function()
     if debounce then
           return -- Stops the function, cancels the event
      end
     debounce = true -- Stops the event from running somewhere else

     -- Create the character here

     debounce = false -- Allows the event to run again
end)

Ty! I added it and it worked perfectly fine!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.