Having a problem with coroutine

hey guys,

I seem to be having a problem with yielding a coroutine.

local player = game:GetService("Players").LocalPlayer
repeat wait() until player.Character
local character = player.Character
local mouse = player:GetMouse()
local tool = script.Parent

local idleTrack = Instance.new("Animation")
idleTrack.AnimationId = "rbxassetid://7105595820"
local Animation = character:WaitForChild("Humanoid"):LoadAnimation(idleTrack)

local Enabled = true

local coRunning = true


local newThread = coroutine.create(function()
	while coRunning do
		wait()
		character.Humanoid.Running:Connect(function(speed)
			if speed > 5 then
				Animation:Stop()
			else
				Animation:Play()
			end
		end)
	end
end)




script.Parent.Equipped:Connect(function()
	Animation:Play()
	coRunning = true
	coroutine.resume(newThread)
	tool.Activated:Connect(function()
		if Enabled == true then
			script.RemoteEvent:FireServer("Combat", character.HumanoidRootPart.CFrame*CFrame.new(0,0,-2).p)
		end
	end)	
end)


script.Parent.Unequipped:Connect(function()
	coroutine.yield(newThread)
	Animation:Stop()
	coRunning = false
	print("stopped")
end)

I thought Yield was used to “pause” a coroutine until called upon again?
Unequipped function never goes past the Yield line.
I get no errors.

Any ideas?

I think you don’t really need a coroutine here, you could just store the RBXScriptConnection returned from your Connect function(for Humanoid.Running) and disconnect it when your tool is unequipped, e.g:

local RunConnect 

-- tool equipped
RunConnect = character.Humanoid.Running:Connect(function()
     -- code
end)

-- tool unequipped
RunConnect:Disconnect()

but how would I transition from Idle to Run animation then?

Your connect function should work as intended if you put your current code (below) into it

Screen Shot 2021-07-17 at 7.49.49 PM

1 Like

oh yes, ur right. Thank you. Fixed my problem.
I tend to make it hard for myself lol

1 Like