Roblox新手制作增益脚本遇LocalPlayer索引nil报错求助
解决Roblox增益道具脚本的"attempt to index nil with 'LocalPlayer'"报错
报错原因
你当前用的是服务器脚本(Workspace里的Script属于服务器端执行环境),但Players.LocalPlayer是仅能在**客户端脚本(LocalScript)**里使用的属性。服务器环境下无法获取LocalPlayer,所以代码里Players.LocalPlayer会返回nil,触发"attempt to index nil with 'LocalPlayer'"错误。
修正后的脚本
local Players = game:GetService("Players") script.Parent.Touched:Connect(function(hit) local character = hit.Parent local humanoid = character:FindFirstChild("Humanoid") local player = Players:GetPlayerFromCharacter(character) -- 确保角色有人形对象且能找到对应玩家 if humanoid and player then humanoid.MaxHealth = math.huge humanoid.Health = math.huge humanoid.WalkSpeed = 36 humanoid.JumpPower = 10 end end)
关键修改说明
- 用
game:GetService("Players")规范获取Players服务,避免全局调用的潜在问题 - 通过
Players:GetPlayerFromCharacter(character)从触碰的角色模型关联到对应玩家,这是服务器端获取玩家的标准方式 - 增加
humanoid and player双重判断,避免因无效角色或非玩家角色触发后续错误 - 直接通过找到的
humanoid对象修改属性,无需绕路Player.Character,逻辑更简洁高效
内容的提问来源于stack exchange,提问作者Cold Soda
相关产品推荐
相关产品推荐

