Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 4 years ago

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

Log in to vote
1
Answered by 4 years ago

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!

0
thanks a lot! Darksniper600 104 — 4y
0
No problem! Glad to help! killerbrenden 1537 — 4y
Ad
Log in to vote
1
Answered by 4 years ago

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

Answer this question