Task.cancel(tread) not working

I am working on a placement system and i use task.spawn to show the preview and task.cancel to stop that, the issue is it doesn’t seem to work, with the spawned task still continueing after i did task.cancel.

Code:

local thread
local Model

local function Placement(Model)
	RunService.RenderStepped:Connect(function() 
		print(Model)
	end)
end

UserInputService.InputBegan:Connect(function(Input, IsChatting)
	if IsChatting then return end
	if script.Parent.Parent ~= Players.LocalPlayer.Character then return end

	if Input.KeyCode == Enum.KeyCode.E then
		if not Showing then
			print("on")
			Model = ReplicatedStorage.CookingRemotes[script.Parent.Name]:Clone()
		    Mouse.TargetFilter = Model
		    Model:PivotTo(CFrame.new() * CFrame.Angles(math.rad(0), math.rad(Players.LocalPlayer.Character.Torso.Rotation.Y), math.rad(0)))
			Showing = true
			Model.Parent = workspace
			thread = task.spawn(Placement, Model)
		else
			print("off")
			task.cancel(thread)
			Showing = false
			Model:Destroy()
		end
	end
end)


script.Parent.Unequipped:Connect(function()
	if Showing then
		task.cancel(thread)
		Showing = false
		Model:Destroy()
	end
end)

Any help is appreciated!

If you’re seeing print(Model) in your console even after task cancel, it’s because you’ve added a callback listener to the RenderStepped signal, when you started the task.

Imagine it like that:

  1. You started a task
  2. You added callback to the RenderStepped signal
  3. You cancelled the task

Cancelling task won’t destroy the callback you’ve added.
Your solution would be not using tasks, but rather run the function Placement(Model) immediately, and when the item is not showed, destroy the callback.

local signalHandle
local function Placement(Model)
    signalHandle = RunService.RenderStepped:Connect(function() 
        print(Model)
    end)
end
local function StopPlacement()
    signalHandle:Disconnect()
end

And instead of creating task, you’ll just call Placement(Model) and instead of canceling task, you’ll call StopPlacement().

2 Likes

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