This repository has been archived on 2023-02-02. You can view files and clone it, but cannot push or open issues or pull requests.
mfgames-gallium-cil/src/MfGames.Gallium/SelectComponentOrDefaultExt...

53 lines
1.6 KiB
C#

using System;
using System.Collections.Generic;
namespace MfGames.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;
}
}
}