feat: introduced SelectComponent and SelectComponentOrDefault

This commit is contained in:
Dylan R. E. Moonfire 2022-07-09 16:59:15 -05:00
parent 7206932f63
commit 4e21b3b6f5
2 changed files with 101 additions and 0 deletions

View file

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
namespace Gallium;
/// <summary>
/// Extension methods for selecting components from a list.
/// </summary>
public static class SelectComponentExtensions
{
/// <summary>
/// Retrieves a component from an entity and return it. If the entity does not have
/// the component, it will be
/// filtered out.
/// </summary>
/// <param name="entities">The entities to process.</param>
/// <typeparam name="T1">The component type being searched.</typeparam>
/// <returns>A sequence of T1.</returns>
public static IEnumerable<T1> SelectComponent<T1>(this IEnumerable<Entity> entities)
{
foreach (Entity entity in entities)
{
if (entity.TryGet(out T1 v1))
{
yield return v1;
}
}
}
/// <summary>
/// Retrieves a component from an entity and return it. If the entity does not have
/// the component, it will be filtered out.
/// </summary>
/// <param name="entities">The entities to process.</param>
/// <param name="t1">The component type being searched.</param>
/// <returns>A sequence of T1.</returns>
public static IEnumerable<object> SelectComponent(
IEnumerable<Entity> entities,
Type t1)
{
foreach (Entity entity in entities)
{
if (entity.Has(t1))
{
yield return entity.Get<object>(t1);
}
}
}
}

View file

@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
namespace Gallium;
/// <summary>
/// Extension methods for selecting components from a list.
/// </summary>
public static class SelectComponentOrDefaultExtensions
{
/// <summary>
/// Retrieves a component from an entity and return it. If the entity does not have
/// the component, then null will be returned.
/// </summary>
/// <param name="entities">The entities to process.</param>
/// <param name="t1">The component type being searched.</param>
/// <returns>A sequence of T1 or nulls.</returns>
public static IEnumerable<object?> SelectComponent(
IEnumerable<Entity> entities,
Type t1)
{
foreach (Entity entity in entities)
{
if (entity.Has(t1))
{
yield return entity.Get<object>(t1);
}
yield return null;
}
}
/// <summary>
/// Retrieves a component from an entity and return it. If the entity does not have
/// the component, then the default value will be returned.
/// </summary>
/// <param name="entities">The entities to process.</param>
/// <typeparam name="T1">The component type being searched.</typeparam>
/// <returns>A sequence of T1.</returns>
public static IEnumerable<T1?> SelectComponentOrDefault<T1>(this IEnumerable<Entity> entities)
{
foreach (Entity entity in entities)
{
if (entity.TryGet(out T1 v1))
{
yield return v1;
}
yield return default;
}
}
}