Garry's Mod crashes when I call the Remove( ) function on init.lua

I am trying to remove the prop in front of the player using the Remove( ) function in init.lua in my gamemode. But sometimes when I call it the game crashes. it seems completely random sometimes it crashes the first time I call it some times the third. I am calling it using datastream.StreamToServer() from the client if that matters. I’ll post my code.

from cl_init.lua
[lua]function KeyPressed(P,Key)
local trace = P:GetEyeTrace()
if Key == IN_USE then

		if trace.Entity:GetModel() == "models/rocco/apple.mdl" then
			local proppos = trace.Entity:GetPos()
			if proppos:Distance(P:GetPos()) <= 128 then
				inventory.apples = inventory.apples + 1
				datastream.StreamToServer( "remove" )
			end	
		end
		
		if trace.Entity:GetModel() == "models/rocco/log.mdl" then
			local proppos = trace.Entity:GetPos()
			if proppos:Distance(P:GetPos()) <= 128 then
				inventory.log = inventory.log + 100
				datastream.StreamToServer( "remove" )
			end	
		end
end	

end
hook.Add( “KeyPress”, “KeyPressedHook”, KeyPressed )[/lua]

from init.lua
[lua]function remove(ply)
local trace = ply:GetEyeTrace()
timer.Create( “removetimer” , 0.1,1,
function()
trace.Entity:Remove()
end)
end
datastream.Hook( “remove”, remove )[/lua]

I have a timer on the remove function because if I don’t the server will remove the prop before the client gets the model data.

Why why why are you using datastream? It might solve the problem just to switch to concommands. just change your remove function to

[lua]function remove(ply)
local trace = ply:GetEyeTrace()
timer.Create( “removetimer” , 0.1,1,
function()
trace.Entity:Remove()
end)
end
concommand.Add( “removeEnt”, remove )[/lua]

And change your datastream.StreamToServer to

[lua]RunConsoleCommand("removeEnt’);[/lua]

That seemed to have solved the problem thanks!

KeyPress is serverside too

make it shared

[lua]
local function KeyPressed(P,Key)
local entity = P:GetEyeTrace().Entity

if Key == IN_USE and entity:IsValid() then
	if entity:GetModel():lower() == "models/rocco/apple.mdl" then
		if entity:GetPos():Distance(P:GetPos()) <= 128 then
			if CLIENT then
				inventory.apples = inventory.apples + 1
			else
				entity:Remove()
			end
		end
	end

	if entity:GetModel() == "models/rocco/log.mdl" then
		if entity:GetPos():Distance(P:GetPos()) <= 128 then
			if CLIENT then
				inventory.log = inventory.log + 100
			else
				entity:Remove()
			end
		end
	end
end

end

hook.Add( “KeyPress”, “KeyPressedHook”, KeyPressed )
[/lua]