简体   繁体   中英

"attempt to index nil with 'MoveDirection'"

I am making a script which changes the footstep sound of the player but it keeps returning with the error message "attempt to index nil with 'MoveDirection'.

local runService = game:GetService("RunService")
local player = game:GetService("Players").LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local human = character:FindFirstChild("Humanoid")


runService.RenderStepped:Connect(function()
    if human.MoveDirection.Magnitude > 0 then -- walking
        game.SoundService.WalkingSound.Playing = true
    else -- if player not walking
        game.SoundService.WalkingSound.Playing = false
    end
end)

I have tried changing variables and double checking spelling, still returns back with an error message.

any help is appreciated.

Where is this script located in? if its not in somewhere runs every time the player dies (for example StarterPlayer.StarterCharacterScripts ) your code wont work since the humanoid object attached to human variable no longer exists. (and you would get the attempt to index nil with 'MoveDirection' error) or if its already in an place where the scripts in it runs everytime player dies try using:WaitForChild() instead of:FindFirstChild() at line 4

use this:

local human = character:WaitForChild("Humanoid")

instead of this:

local human = character:FindFirstChild("Humanoid")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM