Weird stuff going on in cl_init.lua aka "Tried to use a NULL entity!"

I keep getting this error:


[ERROR] gamemodes/projectbic/gamemode/cl_init.lua:30: Tried to use a NULL entity!
  1. Health - [C]:-1
   2. unknown - gamemodes/projectbic/gamemode/cl_init.lua:30


and here is my code:



ply = LocalPlayer();
function GM:RenderScreenspaceEffects()
	local tab = {
		[ "$pp_colour_addr" ] = 0,
		[ "$pp_colour_addg" ] = 0,
		[ "$pp_colour_addb" ] = 0,
		[ "$pp_colour_brightness" ] = 0,
		[ "$pp_colour_contrast" ] = 1,
		[ "$pp_colour_colour" ] = ply:Health() / ply:GetMaxHealth(), --line 30
		[ "$pp_colour_mulr" ] = 0,
		[ "$pp_colour_mulg" ] = 0,
		[ "$pp_colour_mulb" ] = 0
	};
	DrawColorModify(tab)
end

Now, the really weird thing is, that when I make a change in the file while gmod runs, it works as it should, and the color gets greyed out, but when I restart the game with the same changes, I get the bug again.

Example change (adding if statement):



ply = LocalPlayer();
function GM:RenderScreenspaceEffects()
    if ( CLIENT ) then
	local tab = {
		[ "$pp_colour_addr" ] = 0,
		[ "$pp_colour_addg" ] = 0,
		[ "$pp_colour_addb" ] = 0,
		[ "$pp_colour_brightness" ] = 0,
		[ "$pp_colour_contrast" ] = 1,
		[ "$pp_colour_colour" ] = ply:Health() / ply:GetMaxHealth(), --line 30
		[ "$pp_colour_mulr" ] = 0,
		[ "$pp_colour_mulg" ] = 0,
		[ "$pp_colour_mulb" ] = 0
	};
	DrawColorModify(tab);
    end
end

Anybody got a clue about why this is happening and how to fix it?

LocalPlayer isn’t available when the file runs for the first time. Move the call into the function.

You need to wait until LocalPlayer exists.

You’re making “ply” global by the looks of it, don’t do that, something external could redefine it and break your code.

That’s because when gmod is loaded, your LocalPlayer exists. When you cause a lua refresh it will assign “ply” to a valid entity.

LocalPlayer() does not exist until just after DrawOverlay is called for the first time.

Simple fix:

Define ply inside the hook,
Check if is valid.





function GM:RenderScreenspaceEffects()
    local ply = LocalPlayer(); // Tada
    if ( CLIENT and IsValid(ply) ) then // Tada!!!
	local tab = {
		[ "$pp_colour_addr" ] = 0,
		[ "$pp_colour_addg" ] = 0,
		[ "$pp_colour_addb" ] = 0,
		[ "$pp_colour_brightness" ] = 0,
		[ "$pp_colour_contrast" ] = 1,
		[ "$pp_colour_colour" ] = ply:Health() / ply:GetMaxHealth(), --line 30
		[ "$pp_colour_mulr" ] = 0,
		[ "$pp_colour_mulg" ] = 0,
		[ "$pp_colour_mulb" ] = 0
	};
	DrawColorModify(tab);
    end
end






Thanks a lot, that’s actully pretty useful information :slight_smile: