encompass-cs-docs/content/concepts/component.md

48 lines
1.4 KiB
Markdown
Raw Permalink Normal View History

2019-05-22 20:56:04 +00:00
---
title: "Component"
date: 2019-05-22T12:51:29-07:00
weight: 5
---
2020-07-21 00:30:09 +00:00
A Component is a structure of related data.
2019-05-22 20:56:04 +00:00
2019-12-01 21:43:31 +00:00
```cs
using Encompass;
using System.Numerics;
2019-05-22 20:56:04 +00:00
2021-05-01 19:07:59 +00:00
public struct VelocityComponent {
2020-07-12 19:09:27 +00:00
public Vector2 Velocity { get; }
public VelocityComponent(Vector2 velocity)
{
Velocity = velocity;
}
2019-05-22 20:56:04 +00:00
}
```
2019-12-01 21:43:31 +00:00
Components are attached to Entities with the **SetComponent** method.
2019-05-22 20:56:04 +00:00
2019-12-01 21:43:31 +00:00
```cs
using Encompass;
...
var worldBuilder = new WorldBuilder();
var entity = worldBuilder.CreateEntity();
2020-07-12 19:09:27 +00:00
worldBuilder.SetComponent(entity, new VelocityComponent(Vector2.One));
2019-05-22 20:56:04 +00:00
```
2019-12-01 21:43:31 +00:00
**SetComponent** can also be used from within an **Engine**. We will talk more about this later.
2020-07-11 00:06:40 +00:00
Components are always structs, meaning they follow value-type semantics. If you are used to working with classes you might find this confusing.
2020-07-12 19:09:27 +00:00
One major point of difference is that value types are _copied_ rather that passed by reference by default.
2020-07-11 00:06:40 +00:00
2020-07-12 19:09:27 +00:00
You can read more about value types here: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/value-types
2020-07-11 00:06:40 +00:00
If you use them idiomatically, you don't have to worry about them creating garbage collection pressure, so this is a big win for performance when working in C#.
2019-05-22 20:56:04 +00:00
{{% notice warning %}}
2019-12-01 21:43:31 +00:00
Components should **never** reference other Components directly. This breaks the principle of loose coupling. You **will** regret it if you do this.
2019-05-22 20:56:04 +00:00
{{% /notice %}}