Revision Difference
Entity_Components#546278
<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>() )
{
}
}
}
```
⤶
# 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.⤶
⤶
```csharp⤶
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