Garry's Mod Wiki

Revision Difference

GM:OnEntityCreated#527204

<function name="OnEntityCreated" parent="GM" type="hook"> <ishook>yes</ishook> <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 <page>Global.IsValid</page>.</note> <warning>Removing the created entity during this event can lead to unexpected problems. Use <page>timer.Simple</page>( 0, .... ) to safely remove the entity.</warning> </description> <realm>Shared</realm> <predicted>No</predicted> <args> <arg name="entity" type="Entity">The entity</arg> </args> </function> <example> <description>When a prop spawns it yells.</description> <code> function GM:OnEntityCreated( ent ) hook.Add( "OnEntityCreated", "PropScream", function( ent ) if ( ent:GetClass() == "prop_physics" ) then ent:EmitSound( "vo/npc/male01/no02.wav" ) end end⤶ end )⤶ </code> </example> <example> <description>Adds all props and ragdolls into a list. More efficient alternative to looping over ents.GetAll().</description> <code> 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⤶ ⤶ EntList[ ent:EntIndex() ] = ent⤶ end ) </code> </example>