2021-09-07 05:15:45 +00:00
|
|
|
using System;
|
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.Linq;
|
2022-06-05 18:44:51 +00:00
|
|
|
|
2021-09-07 05:15:45 +00:00
|
|
|
using Gallium;
|
|
|
|
|
2022-06-05 18:44:51 +00:00
|
|
|
namespace Nitride.Contents;
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
/// Various extension methods for working with content.
|
|
|
|
/// </summary>
|
|
|
|
public static class EntityContentExtensions
|
2021-09-07 05:15:45 +00:00
|
|
|
{
|
|
|
|
/// <summary>
|
2022-06-05 18:44:51 +00:00
|
|
|
/// Retrieves the single registered content entity inside the component.
|
|
|
|
/// If there is more than one, this will throw an exception.
|
2021-09-07 05:15:45 +00:00
|
|
|
/// </summary>
|
2022-06-05 18:44:51 +00:00
|
|
|
/// <param name="entity">The entity to query.</param>
|
|
|
|
/// <returns>The one and only content component.</returns>
|
|
|
|
public static IContent GetContent(this Entity entity)
|
2021-09-07 05:15:45 +00:00
|
|
|
{
|
2022-06-05 18:44:51 +00:00
|
|
|
Type type = entity.GetComponentTypes().Single(x => typeof(IContent).IsAssignableFrom(x));
|
2021-09-07 05:15:45 +00:00
|
|
|
|
2022-06-05 18:44:51 +00:00
|
|
|
return entity.Get<IContent>(type);
|
|
|
|
}
|
2021-09-07 05:15:45 +00:00
|
|
|
|
2022-06-05 18:44:51 +00:00
|
|
|
/// <summary>
|
|
|
|
/// Determines if the entity has at least one content component.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="entity">The entity to inspect.</param>
|
|
|
|
/// <returns>True if there is a component extending `IContent`.</returns>
|
|
|
|
public static bool HasContent(this Entity entity)
|
|
|
|
{
|
|
|
|
return entity.GetComponentTypes().Any(x => typeof(IContent).IsAssignableFrom(x));
|
|
|
|
}
|
2021-09-07 05:15:45 +00:00
|
|
|
|
2022-06-05 18:44:51 +00:00
|
|
|
/// <summary>
|
|
|
|
/// Remove all existing content components from the entity and then adds
|
|
|
|
/// the new component into the entity before returning it.
|
|
|
|
/// </summary>
|
|
|
|
/// <param name="entity">The entity to query and modify.</param>
|
|
|
|
/// <param name="content">The content to add to the entity.</param>
|
|
|
|
/// <typeparam name="TType">The base type of the content.</typeparam>
|
|
|
|
/// <returns>The entity or a copy with the new component.</returns>
|
|
|
|
public static Entity SetContent<TType>(this Entity entity, TType content)
|
|
|
|
where TType : IContent
|
|
|
|
{
|
|
|
|
IEnumerable<Type>? existing = entity.GetComponentTypes().Where(x => typeof(IContent).IsAssignableFrom(x));
|
2021-09-07 05:15:45 +00:00
|
|
|
|
2022-06-05 18:44:51 +00:00
|
|
|
foreach (Type? component in existing)
|
|
|
|
{
|
|
|
|
entity = entity.Remove(component);
|
2021-09-07 05:15:45 +00:00
|
|
|
}
|
2022-06-05 18:44:51 +00:00
|
|
|
|
|
|
|
return entity.Add(content);
|
2021-09-07 05:15:45 +00:00
|
|
|
}
|
|
|
|
}
|