You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

编写Lua脚本实现Shift键冲刺功能时遇“attempt to index nil”错误

问题解决:Shift冲刺脚本的"attempt to index nil"错误

错误根源

你代码里的UserInputSerive拼写错误,正确的服务名是UserInputService。这个拼写错误会导致变量UserInputSerive为nil,当你尝试调用它的InputBegan或InputEnded事件时,就会触发"attempt to index nil"错误。

另外还有一个潜在问题:当角色死亡或重新加载时,原有的Character和Humanoid会失效,此时脚本无法继续正常工作,需要监听角色创建事件来更新引用。

修正后的完整代码

local UserInputService = game:GetService("UserInputService")
local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:WaitForChild("Humanoid")

-- 监听角色重建,更新Character和Humanoid引用
Player.CharacterAdded:Connect(function(newChar)
    Character = newChar
    Humanoid = Character:WaitForChild("Humanoid")
end)

UserInputService.InputBegan:Connect(function(input, gameProcessed)
    -- 忽略游戏已处理的输入(比如聊天框输入时)
    if gameProcessed then return end
    if input.KeyCode == Enum.KeyCode.LeftShift then
        Humanoid.WalkSpeed = 35
    end
end)

UserInputService.InputEnded:Connect(function(input, gameProcessed)
    if gameProcessed then return end
    if input.KeyCode == Enum.KeyCode.LeftShift then
        Humanoid.WalkSpeed = 16
    end
end)

额外优化说明

  • 增加了gameProcessed判断:当玩家在聊天框等UI中输入时,不会触发冲刺逻辑,避免误操作。
  • 新增CharacterAdded监听:确保角色重建后,脚本能重新获取有效的Humanoid引用,避免后续操作报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 00:15:58