Auanorli
Auanorli

Reputation: 1

Attempt to call global 'localPlayer' (a nil value) error in Garry's Mod

I need help with my code, when I run it I get the error 'attempt to call global 'localPlayer' (a nil value)' I want to make a hunger system in sandbox in my own hud. I found an addon with food there I took models and scripts and instead of getting hp, I need the variable with food to change, but there is a lot of food and a separate script is allocated for each food

here my code

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()

    local ply = LocalPlayer()
    --local currentHungerLevel = ply:GetNWInt('foodSostoyanie') or 100
    --ply:SetNWInt('foodSostoyanie', math.Clamp(currentHungerLevel - 10, 0, 100))
    --activator:SetHealth(activator:Health()-10)
    --local foodSostoyaniee = require "clientloa.lua"
    --foodSostoyaniee = foodSostoyanie
    --local food = foodSostoyanie - 5
    local currentHungerLevel = ply:GetNWInt('hunger_level') or 100
    --ply:SetNWInt('hunger_level', math.Clamp(currentHungerLevel + 10, 0, 100))
    self.Entity:Remove()
    activator:EmitSound("eating_and_drinking/drinking.wav", 50, 100)
    
end

Upvotes: 0

Views: 1549

Answers (1)

GPlayer
GPlayer

Reputation: 131

LocalPlayer() is a global function accessible only on client. The ENT:Use hook is accessible only on server, so you are trying to access a clientside only function on a server. Think about it - local player does not make a sense on the server, it only makes sense on the client - it represents a player entity. If you want to access the player that have used the entity - use a ENT:Use parameters:

function ENT:Use(activator, caller, useType, value)
   //Heal the user
   activator:SetHealth(activator:Health() + 10)
end

Refer to this page on garry's mod wiki: https://wiki.facepunch.com/gmod/ENTITY:Use

Upvotes: 1

Related Questions