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

Why is only the first part of my script is running?

I am trying to make my cow walk in my game but only the first part of my script runs. This is what I came up with:

	local animation = script.Parent.Animation
	local humanoid = script.Parent.Humanoid
	local animationTrack = humanoid:LoadAnimation(animation)
	local cow = script.Parent


while true do
	wait(1)
if script.Parent.HumanoidRootPart.Velocity.Magnitude >= 6 then
		animationTrack:Play()
		print("playing")
	end
end

while true do
	wait(1)
if script.Parent.HumanoidRootPart.Velocity.Magnitude <= 5 then
		animationTrack:Stop()
		print("Stopped")
	end
end

What I mean by only the first part is if I switch the second while true script to the first then it will run. (It only works up to line 13) but says it all runs

2 answers

✓ Accepted answer

You're trying to do 2 while loops in the same script. This will not work as they are running in the same thread.

You don't even need 2 while loops, you just need 1 loop and an if then elseif end statement.

Use Coroutine's to fix this, run each while loop in a different thread!

local cow = script.Parent
local animation = cow.Animation
local humanoid = cow.Humanoid
local track = humanoid:LoadAnimation(animation)

local animFunction = coroutine.wrap(function()
	while wait(1) do
		if cow.HumanoidRootPart.Velocity.Magnitude >= 6 then
			track:Play()
			print("Playing")
		elseif cow.HumanoidRootPart.Velocity.Magnitude <= 5 then
			track:Stop()
			print("Stopped")
		end
	end
end)

animFunction()

Hope this helped! Feel free to select this as an answer if this helped you!

2 comments

0

thanks a lot!

0

No problem! Glad to help!

The first while loop is preventing the second one to run. Since the first loop never ends, the second loop never has a chance to start. In your case, this could simply be solved by merging the two.

local animation = script.Parent.Animation
local humanoid = script.Parent.Humanoid
local animationTrack = humanoid:LoadAnimation(animation)
local cow = script.Parent

while true do
	wait(1)
	if script.Parent.HumanoidRootPart.Velocity.Magnitude >= 6 then
		animationTrack:Play()
		print("playing")
	elseif script.Parent.HumanoidRootPart.Velocity.Magnitude <= 5 then
		animationTrack:Stop()
		print("Stopped")
	end
end	

In other cases where you really need to have both loops running simultaneously, you'd use coroutines. Generally though, the fewer threads, the faster the performance

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