编写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
相关产品推荐
相关产品推荐

