EHandle

From Sven Co-op
Revision as of 19:30, 13 February 2025 by Outerbeast (talk | contribs)
Jump to navigation Jump to search

This type is used to store a handle to an entity across multiple frames. If the entity is removed, EHandle will return null instead. Using EHandle is very easy:

EHandle g_hHandle;

void StoreEntity( CBaseEntity@ pEntity )
{
    g_hHandle = pEntity; // CBaseEntity@ (and child types) instances implicitly cast to EHandle
}

void DoSomethingWithStoredEntity()
{
    if( g_hHandle ) // Check if the EHandle is valid first before using it.
    {
        CBaseEntity@ pEntity = g_hHandle.GetEntity();

        //Do something with "pEntity"
    }
}

You should always check if the handle is valid before using it, otherwise, Angelscript will stop executing and raise an error.

You should always use EHandle when storing entity handles, unless you know that it will only be used in current frame. Even then, it is safer to use EHandle to avoid problems.

Never declare a CBase* handle as a global or member variable, always use EHandle.

For the same reason, avoid passing CBase* handles through scheduled function/method parameters. In situations where you have to pass an entity through a scheduled function, its recommended to overload the scheduled function changing the CBase* parameter to EHandle and scheduling that overload:

void ScheduleEntity( CBaseEntity@ pEntity )
{
    // This will schedule "DoSomethingWithEntity( CBaseEntity@ pEntity )" - unsafe, avoid doing this
    // g_Scheduler.SetTimeout( "DoSomethingWithEntity", 0.0f, pEntity );
    
    // This will schedule "DoSomethingWithEntity( EHandle hEntity )" - safe
    g_Scheduler.SetTimeout( "DoSomethingWithEntity", 0.0f, EHandle( pEntity ) );
}


void DoSomethingWithEntity( CBaseEntity@ pEntity ) // Original function
{
    pEntity.DoSomething();
}

void DoSomethingWithEntity( EHandle hEntity ) // Overload
{
    if( hEntity )
        DoSomethingWithEntity( hEntity.GetEntity() );
}