EHANDLE: Difference between revisions

From Valve Developer Community
Jump to navigation Jump to search
mNo edit summary
m (Ehandle moved to EHANDLE)
(No difference)

Revision as of 09:12, 27 April 2009

A 32-bit unique ID for every past or present instance of an entity. The safest way to store off entities that you want to access elsewhere (including across the client-server divide) or at a later time.

You can access CBaseEntity functions directly from an EHANDLE, but to access those of a derived class you must first perform a cast.

Extended description

Entities in the Source Engine are created and deleted all the time. Each time a new entity is instantiated, the engine looks up an unused entity-index and assigns this to the new entity. Once the entity is destroyed, its entity index becomes available again and may be reused for a different entity.

It's often necessary to keep track of an entity. This done mostly with pointers and entindex (index of the entity). However, when the entity is destroyed, using the pointer crashes (because it still points to a non-NULL location) and the entindex is not suitable because it may point to an other entity.

A better and safer way is to use an EHANDLE (or CBaseHandle) to keep track of entities. An EHANDLE encapsulate a 32-bit ID that is unique for an entity instance during the whole game and can be used on both server and client to refer to entity objects (An EHANDLE is a combination of an entity index and an increasing serial number). An EHANDLE can be transformed to CBaseEntity and vice versa just by using its overloaded operators. If an EHANDLE resolves to NULL, the entity is not valid anymore.

Example

// Find a player, if no player is available pPlayer and hPlayer are NULL
CBasePlayer* pPlayer = gEntList.FindEntityByClassname( NULL, "player" );

// Store it in a EHANDLE
EHANDLE hPlayer = pPlayer;

// Convert back to CBasePlayer - must perform intermediate conversion to CBaseEntity to do this!
pPlayer = dynamic_cast<CBasePlayer*>((CBaseEntity*)hPlayer);
Note.pngNote:EHANDLEs must always be converted to the class CBaseEntity first, before casting to a derived class.

See Also