Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Script breaks after respawn?

local tool = script.Parent
local updateMagic = game.ReplicatedStorage:WaitForChild("RemoteEvents").UpdateMagic
local backpack = tool.Parent
local player = backpack.Parent
local character = player.Character or player.CharacterAdded:Wait()                       
local humanoid = character:WaitForChild("Humanoid")  
local moving = false
local meditating = false
local equipped = false
local activated = false

local meditationBar = player.PlayerGui.MeditationBar
local frame = meditationBar.Frame
local progress = frame.Progress


function equip()
	character = player.Character or player.CharacterAdded:Wait()                       
	humanoid = character:WaitForChild("Humanoid")  
	equipped = true
	
end


function unequip()
	equipped = false
	meditating = false
	frame.Visible = false
	tool.med.Disabled = true
end



function onActivation()
	if moving == false and equipped and meditating == false then
		print(moving)
		print(equipped)
		print(meditating)
			frame.Visible = true
			meditating = true
			tool.med.Disabled = false
	end	
end

function moveDetect(speed)
	if equipped then
		if speed > 5 then
			moving = true
			meditating = false
			frame.Visible = false
			tool.med.Disabled = true
			print("moving")
		else
			moving = false
			print("stoppedmoving")
		end
	end
end


tool.Equipped:Connect(equip)
tool.Unequipped:Connect(unequip)
humanoid.Running:Connect(moveDetect)
tool.Activated:Connect(onActivation)

I noticed mainly the move detect area stops working and the frame.Visible = true in activation

1 answer

It fails because you declared the existing Humanoid. After a Player resets, their affiliated avatar gets refreshed; a new Character Rig including all it’s descendants, one of which is a Humanoid. After such an event occurs, the Humanoid you are trying to connect to no longer exists.

To solve your issue, connect all your events under a CharacterAdded signal, to ensure the events retain the current Instances of the Character at all times.

player.CharacterAdded:Connect(function(character)
    local humanoid = character:FindFirstChildOfClass("Humanoid")
    if (humanoid) then
        tool.Equipped:Connect(equip)
        tool.Unequipped:Connect(unequip)
        humanoid.Running:Connect(moveDetect)
        tool.Activated:Connect(onActivation)
    end
end)

Make sure to disconnect all of the tool signals when the Player dies to avoid memory leakage. You can do this with a CharacterRemoving signal too.

This discussion is preserved as it was. New answers, comments, and votes are closed.