GM/OnEntityCreated

From Garry's Mod
Jump to: navigation, search
 GM:OnEntityCreated( )

Contents

Description

Called when the entity is created.

NOTE

Some entities on initial map spawn are passed through this hook, and then removed in the same frame. This is used by the engine to precache things like models and sounds, so always check their validity with IsValid.

WARNING

Removing the created entity during this event can lead to unexpected problems. Use timer.Simple( 0, .... ) to safely remove the entity.

BUG

Despite its name, it is called right after the Entity has been first pushed to Lua, not when the entity is actually created. The amount time between when entity is created and this hook is called is not fixed, and can be infinite in some cases, especially on client. Do not use this hook to reliably detect when an entity is created.

Request Tracker: #1290

This bug will be fixed in the next update.

BUG

LocalPlayer will return NULL if the created entity is the local player.

Issue Tracker: #3763

This bug will be fixed in the next update.

Arguments

Entity entity

The entity

Examples

Example

When a prop spawns it yells.

function GM:OnEntityCreated( ent )
	if ( ent:GetClass() == "prop_physics" ) then
		ent:EmitSound( "vo/npc/male01/no02.wav" )
	end
end


Examples

Example

Adds all props and ragdolls into a list. More efficient alternative to looping over ents.GetAll().

local TrackedEnts =
{
	[ "prop_physics" ] = true,
	[ "prop_ragdoll" ] = true
}

local EntList = {}

hook.Add( "OnEntityCreated", "SoftEntList", function( ent )
	if ( not ent:IsValid() or not TrackedEnts[ ent:GetClass() ] ) then return end
	
	EntList[ ent:EntIndex() ] = ent
end )


Personal tools
Navigation