GM/OnEntityCreated

From Garry's Mod
(Difference between revisions)
Jump to: navigation, search
(Added note about vehicles so people stop freaking out, REMOVE THIS once this behaviour changes.)
(Added example to show that vehicles can still access base entity functions)
Line 3: Line 3:
  
 
'''NOTE:''' In the current version of gmod, vehicles passed to this function will not be considered valid until they're fully spawned.<br>
 
'''NOTE:''' In the current version of gmod, vehicles passed to this function will not be considered valid until they're fully spawned.<br>
As a temporary workaround, see the example below.
+
As a temporary workaround, see the example below. IsValid, GetClass, and any other methods that do not have to access the internal vehicle object will still work, however.
 
|Realm=Shared
 
|Realm=Shared
 
|Predicted=No
 
|Predicted=No
Line 31: Line 31:
 
     end)
 
     end)
 
end
 
end
 +
}}
 +
{{Example
 +
|Description=Adds all props and ragdolls into a list. More efficient alternative to looping over ents.GetAll().
 +
|Code=local TrackedEnts =
 +
{
 +
[ "prop_physics" ] = true,
 +
[ "prop_ragdoll" ] = true
 +
}
 +
 +
local EntList = {}
 +
 +
hook.Add( "OnEntityCreated", "GS - Create Soft Entity List", function( ent )
 +
if ( not ( ent:IsValid() and TrackedEnts[ ent:GetClass() ] ) ) then return end
 +
 +
EntList[ ent:EntIndex() ] = ent
 +
end )
 
}}
 
}}

Revision as of 01:09, 24 January 2016

 GM:OnEntityCreated( )

Contents

Description

Called right after the Entity has been made visible to Lua.

NOTE: In the current version of gmod, vehicles passed to this function will not be considered valid until they're fully spawned.
As a temporary workaround, see the example below. IsValid, GetClass, and any other methods that do not have to access the internal vehicle object will still work, however.

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

When a vehicle is created, wait until the entity is valid and change its color to blue. Without a timer the ent will not validate and you may encounter errors.

function GM:OnEntityCreated( ent )
    timer.Simple( .01, function()
        if IsValid( ent ) and ent:IsVehicle() then
            ent:SetColor( Color( 0, 0, 255 ) )
        end
    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", "GS - Create Soft Entity List", function( ent )
	if ( not ( ent:IsValid() and TrackedEnts[ ent:GetClass() ] ) ) then return end
	
	EntList[ ent:EntIndex() ] = ent
end )


Personal tools
Navigation