S&box Wiki

Revision Difference

Entity_Components#545877

<cat>Code.Misc</cat>⤶ <title>Entity Components</title>⤶ ⤶ Entities can have components. These components are networked, so are also available on the client.⤶ ⤶ # Defining Components⤶ ⤶ ```csharp⤶ public partial class MyComponent : EntityComponent⤶ {⤶ [Net] public string MyVariable { get; set; }⤶ } ⤶ ⤶ ```⤶ ⤶ Components can also have [Events](Event_System).⤶ ⤶ ```⤶ 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.⤶ ⤶ ```csharp⤶ 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>() )⤶ {⤶ ⤶ }⤶ }⤶ }⤶ ```⤶ ⤶ ### Footnotes⤶ ⤶ * Clients are also entities and can have components on Client.Components