Garry's Mod中'attempt to call global 'localPlayer'(nil值)'错误求助
Garry's Mod自定义饥饿系统错误修复:'attempt to call global 'localPlayer' (a nil value)'
问题原因
LocalPlayer()是客户端专属函数,仅能在客户端Lua代码中调用。你的ENT:Use()函数运行在服务器端,调用该函数必然返回nil,触发报错。- 代码中还误用了未定义的
activator变量,实际上ENT:Use()本身自带参数,第一个参数就是触发使用动作的玩家实体。
修复后的完整代码
AddCSLuaFile( "shared.lua" ) include( 'shared.lua' ) function ENT:SpawnFunction( ply, tr ) if !tr.Hit then return end local SpawnPos = tr.HitPos + tr.HitNormal * 1 local ent = ents.Create( "AppleJuice" ) ent:SetPos( SpawnPos ) ent:Spawn() ent:Activate() return ent end function ENT:Initialize() self.Entity:SetModel("models/FoodNHouseholdItems/juicesmall.mdl") self.Entity:PhysicsInit( SOLID_VPHYSICS ) self.Entity:SetMoveType( MOVETYPE_VPHYSICS ) self.Entity:SetSolid( SOLID_VPHYSICS ) self.Index = self.Entity:EntIndex() local phys = self.Entity:GetPhysicsObject() if phys:IsValid() then phys:Wake() end end function ENT:Use( activator ) -- 检查触发实体是否为有效玩家 if !activator:IsPlayer() then return end local currentHungerLevel = activator:GetNWInt('hunger_level') or 100 -- 增加10点饥饿值,限制在0-100区间内 activator:SetNWInt('hunger_level', math.Clamp(currentHungerLevel + 10, 0, 100)) self.Entity:Remove() activator:EmitSound("eating_and_drinking/drinking.wav", 50, 100) end
关键修改点
- 补全
ENT:Use()的参数为activator,该参数直接对应使用实体的玩家,服务器端可安全调用。 - 移除错误的
local ply = LocalPlayer()语句,改用activator操作玩家的饥饿值数据。 - 添加
activator:IsPlayer()有效性检查,避免非玩家实体触发时出现额外错误。 - 启用原本注释的饥饿值修改逻辑,实现食用食物后增加饥饿值的核心功能。
内容的提问来源于stack exchange,提问作者Auanorli
相关产品推荐
相关产品推荐

