66 lines
2.3 KiB
C#
66 lines
2.3 KiB
C#
|
using System;
|
||
|
using System.Collections.Generic;
|
||
|
using System.Linq;
|
||
|
using Gallium;
|
||
|
|
||
|
namespace Nitride.Contents
|
||
|
{
|
||
|
/// <summary>
|
||
|
/// Various extension methods for working with content.
|
||
|
/// </summary>
|
||
|
public static class EntityContentExtensions
|
||
|
{
|
||
|
/// <summary>
|
||
|
/// Retrieves the single registered content entity inside the component.
|
||
|
/// If there is more than one, this will throw an exception.
|
||
|
/// </summary>
|
||
|
/// <param name="entity">The entity to query.</param>
|
||
|
/// <returns>The one and only content component.</returns>
|
||
|
public static IContent GetContent(this Entity entity)
|
||
|
{
|
||
|
Type type = entity
|
||
|
.GetComponentTypes()
|
||
|
.Single(x => typeof(IContent).IsAssignableFrom(x));
|
||
|
|
||
|
return entity.Get<IContent>(type);
|
||
|
}
|
||
|
|
||
|
/// <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));
|
||
|
}
|
||
|
|
||
|
/// <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));
|
||
|
|
||
|
foreach (var component in existing)
|
||
|
{
|
||
|
entity = entity.Remove(component);
|
||
|
}
|
||
|
|
||
|
return entity.Add(content);
|
||
|
}
|
||
|
}
|
||
|
}
|