menu_bookDocumentation

IsValid: Safe Null and Destroyed Object Checking in s&box

calendar_today May 20, 2026 schedule ~1 min read person PatrickJr verified 50

In s&box, destroying a GameObject or Component doesn't erase the C# reference — the variable still holds a non-null but dead object. Use IsValid() instead of null checks.

CSHARP
// ❌ Wrong - reference is still non-null after Destroy()
if ( myObject != null )
    myObject.DoSomething(); // might throw or do nothing

// ✅ Correct - safe even if myObject is null
if ( myObject.IsValid() )
    myObject.DoSomething();

Common Patterns

Guard before use

CSHARP
void Update()
{
    if ( !_target.IsValid() ) return;
    var dist = WorldPosition.Distance( _target.WorldPosition );
}

Filter destroyed objects from lists

CSHARP
_targets.RemoveAll( t => !t.IsValid() );

Async safety

CSHARP
async Task ShootAfterDelay()
{
    await Task.DelaySeconds( 1.0f );
    if ( !this.IsValid() ) return; // object may be destroyed during delay
    FireProjectile();
}
this.IsValid() works on your own components — essential for guarding async callbacks after awaiting. No separate null check is needed since IsValid() handles null references safely.
Was this helpful?