Entity References (SourceMod)

From AlliedModders Wiki
Revision as of 19:06, 23 July 2009 by PRED* (talk | contribs)
Jump to: navigation, search

An entity reference is a combination of a standard entity index (used for all entities in SourceMod previously) and a pseudo-unique serial number that identifies the entity. Since entities are constantly being created and destroyed a cached index doesn't guarantee the underlying entity is the same, references provide a way of verifying the same entity still exists. Generally speaking, if you have an entity index you wish to cache you should convert it to a reference first. All natives (provided by SourceMod) should be able to accept references in place of indexes (wherever the parameter asks for an entity - Not clients), and these will check use the serial to check that the entity index contained in the reference is the same as when the reference was created.

SourceMod now also supports handling of logical (non-networked entities) and these use references exclusively. Natives that used to return an entity index will continue to do so in the case of networked entities (for backwards compatability) and will only return a reference for non-networked ones.

Converting a backwards-compat index/ref to a guaranteed reference for safely caching

new index = GetEntPropEnt(client, Prop_Send, "m_hActiveWeapon");
 
/* Convert our backwards-compat index/ref to a guaranteed reference */
new ref = EntIndexToEntRef(index);

Converting a reference back to an entity index

new index = EntRefToEntIndex(ref);
 
if (index == -1)
{
	/* Reference wasn't valid - Entity must have been deleted */
}

Using References to handle a logic entity

new ent = -1;
 
while ((ent = FindEntityByClassname(ent, "logic_auto")) != INVALID_ENT_REFERENCE)
{
	/** 
	 * Get the entity index from this reference - This works on references and indexes for convenience. 
	 * Should be a number >2048 since logic_auto is a non networked entity 
	 */
	new index = EntRefToEntIndex(ent);
 
	/* Fire an input on this entity - We use the reference version since this includes a serial check */
	AcceptEntityInput(ent, "Kill");
 
}