s&box
RustCounter-Strike 2s&boxDeadlock
Wiki
Get s&box on Steam
Browse
OverviewGetting StartedCreating GamesEngine & ToolsDocumentationCommunity GamesResources
s&boxDocumentationCodeCode BasicsIs Valid
SOURCE 2 · C#
Build and play games with s&box.

Facepunch's game engine and creation platform — make games in C#, or jump straight into community games.

Get s&box on Steam

s&box Wiki

  • Overview
  • Getting Started
  • Creating Games
  • Engine & Tools
  • Documentation
  • Community Games
  • Resources

Tools & Community

  • Getting Started
  • Creating Games
  • Engine & Tools
  • Resources

Platforms

  • RustBattle
  • CSBattle
  • Rust Game Wiki
  • CS2 Skins Wiki
  • Deadlock Wiki

About

  • Official Site
  • Developer Wiki
  • GitHub
  • Get on Steam
NOT AFFILIATED WITH FACEPUNCH STUDIOS · © 2026 s&box Wiki (community)
Docs/Code
Code

IsValid

Destroying a GameObject or Component doesn't erase the C# reference. Any variable that was pointing to it still holds a non-null object - it's just a dead one. Accessing its properties will do nothing useful or throw an exception.

This is why you can't rely on a plain != null check:

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

// ✅ Correct
if ( myObject.IsValid() )
{
    myObject.DoSomething();
}

You do not need to check for null separately. myObject.IsValid() is safe even if myObject is null.

Common Patterns

Checking before use

void Update()
{
    if ( !_target.IsValid() ) return;

    var dist = WorldPosition.Distance( _target.WorldPosition );
}

Filtering a list after a frame

// Remove any destroyed targets from your list
_targets.RemoveAll( t => !t.IsValid() );

Callbacks and delayed code

Async gaps and timers are common places where objects can be destroyed between frames:

async Task ShootAfterDelay()
{
    await Task.DelaySeconds( 1.0f );

    // The object might have been destroyed during the delay
    if ( !this.IsValid() ) return;

    FireProjectile();
}

:::tip this.IsValid() works on your own components too. It's a safe way to guard async callbacks after awaiting. :::

Source: Facepunch/sbox-docs (CC-BY-4.0) · updated 2026-05-05. Read it rendered on the official docs.

More in Code

Advanced Topics
Api Whitelist
Cheat Sheet
Code
Code Basics
Code Generation
Console Variables
Hotloading
← All documentation

Community wiki — not affiliated with Facepunch Studios. For the latest and most authoritative information, see the official developer wiki.