Skip to content

Instantly share code, notes, and snippets.

@Fallbork
Created October 24, 2022 19:05
Show Gist options
  • Save Fallbork/b7b43c909ea3184bf3999e91b6228af2 to your computer and use it in GitHub Desktop.
Save Fallbork/b7b43c909ea3184bf3999e91b6228af2 to your computer and use it in GitHub Desktop.
An EcsSystems derived class capable of querying
#nullable enable
using Leopotam.EcsLite;
using System;
using System.Text;
namespace Systems
{
internal static partial class ExtensionMethods
{
// Code originally written by Brian Rogers in StackOverflow
// Source: https://stackoverflow.com/questions/17480990/
internal static string TypeName(this Type type)
{
if (!type.IsGenericType)
{
return type.Name;
}
StringBuilder sb = new StringBuilder();
sb.Append(type.Name).Append('<');
bool appendComma = false;
foreach (Type t in type.GetGenericArguments())
{
sb.Append(appendComma ? "," : "").Append(TypeName(t));
appendComma = true;
}
sb.Append('>');
return sb.ToString();
}
}
internal class QueryableEcsSystems : EcsSystems
{
public QueryableEcsSystems(EcsWorld defaultWorld, object shared = null) : base(defaultWorld, shared) { }
public override IEcsSystems Add(IEcsSystem system)
{
string key = system.GetType().TypeName();
IEcsSystem? s = GetAllSystems().Find(value => value.GetType().TypeName() == key);
#if DEBUG && !LEOECSLITE_NO_SANITIZE_CHECKS
if (s != null) { throw new System.Exception("System already exists in the current context."); }
#endif
return base.Add(system);
}
public T? GetSystem<T>() where T : IEcsSystem
{
string key = typeof(T).TypeName();
IEcsSystem? system = GetAllSystems().Find(value => value.GetType().TypeName() == key);
#if DEBUG && !LEOECSLITE_NO_SANITIZE_CHECKS
if (system == null) { throw new System.Exception("System does not exist in the current context."); }
#endif
return (T?)system;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment