S&box Wiki

Entities

Entities

Entities are objects that can be placed within the game world, such as props, players, spawnpoints. They can be created and spawned with the C# API.

Entity is the base class for all entities, ModelEntity extends it to provide a model, AnimEntity provides animations.
RenderEntity can be used for custom rendering.

Spawning Entities

Creating a new instance of an Entity class automatically spawns the entity into the world.

Entity myEntity = new MyEntity();

You can also spawn entities by their Library defined name.

Entity entity = Entity.Create("ent_door"); MyEntity myEntity = Entity.Create<MyEntity>("my_entity");

Spawning an Entity calls the virtual method Entity.Spawn() and if replicated on the client Entity.ClientSpawn().

Entities can be created locally clientside - this will call Entity.Spawn() clientside, but not Entity.ClientSpawn().

Events / Overrides

When entities are created and destroyed they are automatically registered to recieve events from the Event System.

partial class MyEntity : Entity { [Event.Tick] void Tick() { Log.Info( $"This is called every tick whilst {this} lives." ); } }

In addition to the event system, entities have plenty of virtual methods you can override, you can use intellisense to find all of them.

public override void Touch( Entity other ) { Log.Info( $"{this} says {other} is touching me." ); }

Networking / Replication

Entities are replicated from the server to clients based on what Entity.Transmit is set to. By default entites are only transmitted to clients that can see them.

partial class MyEntity : Entity { public override void Spawn() { // Always network this entity to all clients Transmit = TransmitType.Always; } }
When an entity is replicated from the server to the client it needs a parameterless constructor to call.

When an entity is replicated any properties marked as a Networked Type are replicated to the entity on the client too.

partial class MyEntity : Entity { [Net] public string MyString { get; set; } }

Components

Entities can have entity components, these are replicated on clients automatically.

partial class MyEntity : Entity { public override Spawn() { Components.Create<MyComponent>(); } }

Deleting Entities

Entities are not garbage collected like a normal C# class as they belong to the world. Entities can be explicitly deleted by calling Entity.Delete(), these entities are then invalid and should not be used anymore.

Any reference to a deleted Entity will return false on Entity.IsValid(), you should use this instead of a null check on entities.

Special Pages


Wikis

?

Render Time: 17ms

DB GetPage 2
Generate Html 2
SaveChanges (1) 8
Render Body 0
Render Sidebar 1