Cleaning up a tool and its events

so i have a basic raycast gun and im trying to clean everything up when the player resets
after reseting i get an error: Players.GeneralBadNews.Backpack.gun.remoteCleaner:9: attempt to index nil with ‘IsA’

heres my cleaner script:

local tool = script.Parent
script.Parent = game.ServerScriptService

local deleteEvent
function respawnCheck(replicator)
	local parent
	local target
	
	if tool.Parent:IsA("Backpack") then
		parent = game.Players
		target = tool.Parent
	elseif tool:FindFirstAncestorWhichIsA("Workspace") then
		parent = tool.Parent.Parent
		target = tool.Parent
	else
		parent = tool.Parent
		target = tool
	end
	
	deleteEvent = parent.DescendantRemoving:Connect(function(child)
		if child == target then
			print("cleaning up")
			replicator:Destroy()
		else
			deleteEvent:Disconnect()
			respawnCheck(replicator)
		end
	end)
end

script.Event.Event:Connect(function(replicator)
	respawnCheck(replicator)
end)

When a player resets their character including children, their (your tool is a child of the character) parent is nil. So, by the time the server sends the event, the character, and your tool are already deleted. Why don’t you just destroy the replicator when the event is fired?

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