Function in script become laggy after his first use [SOLVED✅]

Hello Devs, I have created a script what basically when the player dies all of him part become invisibles, so when I used it for first time it runned good, but when I used it again become laggy


this is the script in server script service
local Service = game.Players

local RS = game:GetService("ReplicatedStorage")
local Storage = RS:WaitForChild("Storage").Main

Service.PlayerAdded:Connect(function(Player)
	Player.CharacterAdded:Connect(function(Char)
		
		local Character = Player.Character or workspace:FindFirstChild(Player.Name)
		local root = Character:WaitForChild("HumanoidRootPart")
		
		local Humanoid = Character:WaitForChild("Humanoid")
		Humanoid.WalkSpeed = 24
		
		local function dead()
			local parts = Character:GetChildren()
			local function Appear(parts, value)
				for _, part in pairs(parts) do
					if part:IsA("Part") or part:IsA("MeshPart") then

						wait()
						part.Transparency = value	

					end
				end
			end
			local Function = coroutine.resume(coroutine.create(function()
				Appear(parts, 1)
			end))
		end

		Humanoid.Died:Connect(function()
			local func_ = coroutine.resume(coroutine.create(function()
				dead()
			end))
		end)
		
	end)
end)

pls help

This code was all over the place, so instead of breaking it down I just rewrote it to help you get a better idea of best practices. If you have any questions let me know

local Players = game:GetService("Players")

local function onPlayerAdded(Player: Player)
    local function onCharacterAdded(Character: Model)
        local Humanoid = Character:WaitForChild("Humanoid") :: Humanoid

        -- The default humanoid walkspeed can be set in StarterPlayer, you dont need to set it via code here.

        Humanoid.Died:Once(function()
            for _, v in Character:GetChildren() do
                if v:IsA("BasePart") then -- Basepart will account for parts and meshparts
                    v.Transparency = 1
                end
            end
        end)
    end

    if Player.Character then
        onCharacterAdded(Player.Character)
    end

    Player.CharacterAdded:Connect(onCharacterAdded)
end

Players.PlayerAdded:Connect(onPlayerAdded)
for _, v in Players:GetPlayers() do
    task.spawn(onPlayerAdded,v) -- This mostly accounts for studio players who join before the event is connected.
end
1 Like

Hi, I used your code but it continues to lag after the first use.

That doesn’t happen to you?
I can’t fix it

Oh my mistake, your code works, thanks!

1 Like

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