Skip to content

Instantly share code, notes, and snippets.

@bddckr
Last active July 13, 2021 20:40
Show Gist options
  • Save bddckr/3efd4fba70c4d713a0b92d77893114a2 to your computer and use it in GitHub Desktop.
Save bddckr/3efd4fba70c4d713a0b92d77893114a2 to your computer and use it in GitHub Desktop.
A small example on how to use the same kind of system for multiple contexts in Entitas 0.37.0(+).
using System.Collections.Generic;
using Components.Miscellaneous;
using Entitas;
using EntitasHelpers;
using JetBrains.Annotations;
public sealed class DestroySystem<TEntity> : ReactiveSystem<TEntity> where TEntity : class, IEntity, new()
{
private readonly Context<TEntity> _context;
private IMatcher<TEntity> _triggerMatcher;
public DestroySystem([NotNull] Context<TEntity> context) : base(context)
{
_context = context;
}
protected override Collector<TEntity> GetTrigger(IContext<TEntity> context)
{
_triggerMatcher = Matcher<TEntity>.AllOf(context.IndexOfComponentType<TEntity, DestroyRequestedComponent>());
return context.CreateCollector(_triggerMatcher);
}
protected override bool Filter(TEntity entity) => _triggerMatcher.Matches(entity);
protected override void Execute(List<TEntity> entities)
{
foreach (var entity in entities)
{
_context.DestroyEntity(entity);
}
}
}
using Entitas;
using JetBrains.Annotations;
public sealed class DestroySystems : Feature
{
public DestroySystems([NotNull] Contexts contexts) : base("Destroy Systems")
{
Add(new DestroySystem<EditorContextEntity>(contexts.editorContext));
Add(new DestroySystem<MapContextEntity>(contexts.mapContext));
Add(new DestroySystem<SettingsContextEntity>(contexts.settingsContext));
}
}
using System;
using System.Collections.Generic;
using Entitas;
using JetBrains.Annotations;
using UnityEngine;
public static class IContextExtensions
{
public static int IndexOfComponentType<TEntity, TComponent>([NotNull] this IContext<TEntity> context)
where TEntity : class, IEntity, new() where TComponent : IComponent
=> Array.IndexOf(context.contextInfo.componentTypes, typeof(TComponent));
[NotNull]
public static int[] IndicesOfComponentTypes<TEntity>([NotNull] this IContext<TEntity> context, [NotNull] IEnumerable<Type> types)
where TEntity : class, IEntity, new()
{
var indices = new List<int>();
foreach (var type in types)
{
Debug.Assert(typeof(IComponent).IsAssignableFrom(type));
indices.Add(Array.IndexOf(context.contextInfo.componentTypes, type));
}
return indices.ToArray();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment