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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 02:45:34