You need to enable JavaScript to run this app. Roblox Lua脚本报错attempted to index nil with Humanoid求解
优惠活动
大模型
产品
解决方案
定价
更多

Roblox Lua脚本报错attempted to index nil with Humanoid求解

问题定位

报错attempted to index nil with Humanoid的直接原因是,脚本顶层执行local char = player.Character时,玩家角色尚未被引擎加载完成,此时char值为nil,后续执行char.Humanoid相当于对nil值索引属性,直接触发报错。
你的脚本还存在4个会导致运行异常的隐藏问题:

  • 代码括号闭合错误,InputBegan的回调函数内多写了一个end,本身就有语法问题
  • 没有处理玩家角色重生的场景,角色死后重生旧的char、human变量会失效,脚本直接报废
  • 没有判断输入事件的processedEvent返回值,玩家在聊天框打字、操作UI时按F也会误触发动画
  • 用已经不推荐的Humanoid:LoadAnimation接口加载动画,在部分新版本客户端下可能出现兼容性问题
修复后可直接运行的代码
local animationstomp = script.Animation
local user = game:GetService("UserInputService")
local player = game.Players.LocalPlayer

-- 初始化角色相关实例,兼容首次加载和重生场景
local char, humanoid, animator
local function setupCharacter()
    char = player.Character or player.CharacterAdded:Wait()
    humanoid = char:WaitForChild("Humanoid")
    animator = humanoid:WaitForChild("Animator")
end
setupCharacter()
player.CharacterAdded:Connect(setupCharacter)

user.InputBegan:Connect(function(input, isProcessed)
    -- 输入被UI/聊天系统占用时不响应
    if isProcessed then return end
    if input.KeyCode == Enum.KeyCode.F then
        -- 避免重复按F导致动画叠加播放
        local isStompPlaying = false
        for _, track in animator:GetPlayingAnimationTracks() do
            if track.Animation == animationstomp then
                isStompPlaying = true
                break
            end
        end
        if not isStompPlaying then
            local track = animator:LoadAnimation(animationstomp)
            track:Play()
        end
    end
end)
修改点说明
  • 用WaitForChild和CharacterAdded事件保证所有依赖的实例加载完成后再执行逻辑,从根源解决nil索引报错
  • 新增角色重生监听,每次角色刷新后重新获取相关实例,避免重生后脚本失效
  • 增加输入占用判断,避免操作UI、聊天时误触发动画
  • 改用官方推荐的Animator对象加载动画,兼容所有当前版本的Roblox客户端
  • 增加重复播放校验,避免连按F导致多个动画轨道同时播放的异常

内容的提问来源于stack exchange,提问作者therealweldtool

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 13:51:46