Max amount of a certain entity

I was wondering if it possible to make it so you can only spawn one entity at a time? for example darkrp gives the option to choose the max amount of printers you can own i want to do that just with my own entity, any help would be appreciated.

Well, last time I wanted to do that, I did this in the SpawnFunction of my entity:



if ( next( ents.FindByClass( 'your_entity_class' ) ) ~= nil ) then return end


What that does is that it tries to find any entities that are currently spawned that have your entity’s class, then it puts any entities that it can find in a table, then it checks if the next key of that table isn’t nil, meaning it checks if there’s at least one thing in the table, and if there is one thing in the table, it means the entity is already spawned, so if that’s the case, it returns nothing to end the SpawnFunction, so it’s not possible for another entity to spawn of the same class.

You can find your entity’s class usually by just looking at the title of the Lua file it’s code is in - or by just using the third argument passed to the SpawnFunction as the post below said

[editline]20th March 2016[/editline]

Sorry, that’s a bit of a stupid explanation, but you’ll probably get it

The third argument to SpawnFunction is the class name for the entity.

I dont think I have done this correctly ( ive never used spawnfunction ) I have done the following and it doesnt spawn at all.


function ENT:SpawnFunction()
	if ( next( ents.FindByClass( 'trbababaap' ) ) ~= nil ) then return end
end

like i said, doesnt spawn and I dont get any lua errors, I also tried


function ENT:SpawnFunction( ply, tr, ClassName )
	if ( next( ents.FindByClass( 'trbababaap' ) ) ~= nil ) then return end
	local ent = ents.Create( 'trbababaap' )
	ent:Spawn()
	ent:Activate()
end

but got the same result, what is it i’ve done wrong?

Perhaps try



function ENT:SpawnFunction( ply, tr, ClassName )

	if ( !tr.Hit ) or ( next( ents.FindByClass( ClassName ) ) ~= nil ) then return end

	local SpawnPos = tr.HitPos + tr.HitNormal * 10

	local ent = ents.Create( ClassName )
	ent:SetPos( SpawnPos )
	ent:Spawn()
	ent:Activate()

end


If that doesn’t work then you might want to try doing different things to spawn the entity (you should try to spawn it correctly first before trying to stop it from spawning)

It works! you are acutally the most helpful person thanks again

[editline]20th March 2016[/editline]

Just encountered a problem, the entity spawns once but its global in meaning there can only be one of the entity for the entire server not just the player. I am wanting each player to be able to spawn one.
minor problem that doesnt really bother me: you cant press z to remove it once its spawned.

edit: another big problem, stops the neworking of the cl file so people dont see shit