I am currently developing an Entity Component System variant where entities know about their components. Usually you access components like this:
var camera = myEntity.Get<Camera>();
The problem with this is, I want some objects to always have certain components and access them in a type and null safe way. Instead of doing this:
if( !myEntity.Has<Camera>() )
myEntity.Add<Camera>();
var camera = myEntity.Get<Camera>();
I'd rather use:
var entity = World.CreateEntityWith<Camera,Position,...>();
var camera = entity.Camera;
var position = entity.Position;
The only way I could think of was using interfaces and implementing this like:
public interface ICameraHoldingEntity
{
Camera Camera { get; }
}
public interface IPositionHoldingEntity
{
Position Position { get; }
}
public class CameraEntity
: Entity, ICameraHoldingEntity, IPositionHoldingEntity
{
public World World { get; }
public CameraEntity( World world )
{
World = world;
Add<Camera>();
Add<Position>();
}
public Camera Camera => Get<Camera>()!;
public Position Position => Get<Position>()!;
}
This obviously has some drawbacks. What if somebody removes this component? What if a second one is added?
Can you think of a more clever way or pattern to achieve what I am trying to do? Rather by composition than by inheritance?
Thank you for reading : )
I am not 100% clear about the meaning of the whole thing.
Why do the generic types have to be mentioned explicitly, if they can be found in the class design anyway based on the properties?
Apart from a corresponding pattern, you would rather use a fluent code in C# today, if it is only about the exploded naming of the properties to be created initially.
ex: