S&box Wiki

Entity Components

Entities can have components, which are code classes that can be attached and detached from Entities via code during gameplay. Because Entity Components are open-ended, they can be used for almost anything from giving players power-ups, to handling advanced NPC AI behaviors. Entity Components are also networked, so they will be available on both the client and server once added to an Entity.

Many other game engines use a component model similar to this, including Unity and Unreal.

Defining Components

public partial class MyComponent : EntityComponent { [Net] public string MyVariable { get; set; } }

Components can also have Events.

public partial class FlyingComponent : EntityComponent { [Event.Tick] public void OnTick() { Entity.Velocity += Vector3.Up * 16.0f; } }

Creating Components

You can create, get and remove components from an Entity at any time, in this example we simply assign them on Spawn.

public partial class MyEntity : Entity { public override Spawn() { var c = Components.Create<MyComponent>(); var c = Components.GetOrCreate<MyComponent>(); var c = Components.Get<MyComponent>(); var c = new MyComponent(); Components.Add( c ); Components.Remove( c ); Components.RemoveAll(); foreach ( var c in Components.GetAll<MyComponent>() ) { } foreach ( var c in Components.GetAll<EntityComponent>() ) { } } }

Binding Components

If you need to frequently access a component and want a reference that is networked between server and client, you can set up the component as a property with the BindComponent attribute.

public partial class MyEntity : Entity { [BindComponent] public MyComponent Component { get; } public override void Spawn() { Components.Create<MyComponent>(); base.Spawn(); } }

Component will now refer to the same networked component on both client and server.

  • Note that you still need to create the component, and you should do so only from the server.
  • You also do not need to assign the component to the property, which should have no setter.

Footnotes

  • Clients are also entities and can have components on Client.Components