Roblox Studio Lua script for random movement with custom animations not working

43 Views Asked by At

This roblox script to move a character randomly using custom animations:

local humanoid = script.Parent:FindFirstChildOfClass("Humanoid")
local animationController = humanoid:FindFirstChildOfClass("Animator")

-- Load the walking animation
local walkingAnimation = Instance.new("Animation")
local walkingTrack = animationController:LoadAnimation("http://www.roblox.com/asset/?id=16626744032")

-- Load the jumping animation
local jumpingAnimation = Instance.new("Animation")
local jumpingTrack = animationController:LoadAnimation("http://www.roblox.com/asset/?id=16636520699")

while true do
    -- Generate random coordinates within a range
    local randomX = math.random(-50, 50)
    local randomZ = math.random(-50, 50)
    
    print("success")
    
    -- Move the NPC to the random position
    humanoid:MoveTo(Vector3.new(randomX, humanoid.RootPart.Position.Y, randomZ))
    
    walkingTrack:Play()
    
    print("still good")

    -- Randomly trigger the jump action
    if math.random() < 0.2 then
        humanoid:Jump()
    end
    
    -- Example: Play the jumping animation when the NPC jumps
    humanoid.Jumping:Connect(function()
        jumpingTrack:Play()
    end)

    -- Wait for a few seconds before the next movement
    wait(3)
end

keeps throwing errors, and i don't know how to fix this.

I have tried to fix it using humanoid:FindFirstChildOfClass() and humanoid:WaitForChild() functions but it still doesn't work.

It throws the "attempt to index nil with 'LoadAnimation'" error under this form of the script:

local humanoid = script.Parent:FindFirstChildOfClass("Humanoid")
local animationController = humanoid:FindFirstChildOfClass("Animator")

-- Load the walking animation
local walkingAnimation = Instance.new("Animation")
local walkingTrack = animationController:LoadAnimation("http://www.roblox.com/asset/?id=16626744032")

-- Load the jumping animation
local jumpingAnimation = Instance.new("Animation")
local jumpingTrack = animationController:LoadAnimation("http://www.roblox.com/asset/?id=16636520699")

and throws the "Infinite yield possible on 'Workspace.test.Humanoid:WaitForChild("Animator")'" warning using this script:

local humanoid = script.Parent:FindFirstChildOfClass("Humanoid")
local animationController = humanoid:WaitForChild("Animator")

-- Load the walking animation
local walkingAnimation = Instance.new("Animation")
local walkingTrack = animationController:LoadAnimation("http://www.roblox.com/asset/?id=16626744032")

-- Load the jumping animation
local jumpingAnimation = Instance.new("Animation")
local jumpingTrack = animationController:LoadAnimation("http://www.roblox.com/asset/?id=16636520699")
0

There are 0 best solutions below