Reputation: 1
I am playing around with LeoEcs and I keep writing the following code:
if(!entity.HasComponent<T>())
return;
ref T comp = ref entity.GetComponent<T>();
This looks pretty tame, but it gets very boilerplaty when you need to check for multiple params at the same time. I would like to join those together into something like:
if(!entity.HasComponent(out ref T comp))
return;
I've tried out ref, it obviously didn't work, but I am wondering if there is a workaround.
Edit: T is a struct, whose value is stored in an array. I need the ref keyword to be able to modify the actual value, instead of its copy.
Upvotes: 0
Views: 74
Reputation: 6327
here is a workaround if you want to achieve a similar effect.
ref var comp = ref entity.GetComponentRef<T>();
public ref T GetComponentRef<T>(int entityId) where T : struct
{
if (!HasComponent<T>(entityId))
{
throw new InvalidOperationException($"Component {typeof(T)} not found for entity {entityId}");
}
return ref components[GetIndex<T>(entityId)];
}
Upvotes: 0