Skip to content

Instantly share code, notes, and snippets.

@grofit
Created April 24, 2020 21:33
Show Gist options
  • Save grofit/0eb4a200ddd3e9cc598c12db90c1c9f9 to your computer and use it in GitHub Desktop.
Save grofit/0eb4a200ddd3e9cc598c12db90c1c9f9 to your computer and use it in GitHub Desktop.
Entity Operation Batching
public class EntityBatchOperation
{
private const int NoComponentTypeId = -1;
private Entity _entity;
private List<int> _componentsAdded = new List<int>();
private List<int> _componentsRemoved = new List<int>();
public EntityBatchOperation(Entity entity)
{
_entity = entity;
}
public void AddComponent<T>(T component, int componentTypeId = NoComponentTypeId) where T : IComponent
{
if (componentTypeId == NoComponentTypeId)
{
var componentType = component.GetType();
componentTypeId = _entity.ComponentTypeLookup.GetComponentType(componentType);
}
var allocationId = _entity.ComponentDatabase.Allocate(componentTypeId);
_entity.InternalComponentAllocations[componentTypeId] = allocationId;
_entity.ComponentDatabase.Set(componentTypeId, allocationId, component);
_componentsAdded.Add(componentTypeId);
}
public void RemoveComponent<T>(T component, int componentTypeId = NoComponentTypeId) where T : IComponent
{
if (componentTypeId == NoComponentTypeId)
{
var componentType = component.GetType();
componentTypeId = _entity.ComponentTypeLookup.GetComponentType(componentType);
}
if (_entity.InternalComponentAllocations[componentTypeId] == Entity.NotAllocated)
{ return; }
_componentsRemoved.Add(componentTypeId);
}
public void Finish()
{
var componentsAddedSubject = (Subject<int[]>) _entity.ComponentsAdded;
var componentsRemovingSubject = (Subject<int[]>) _entity.ComponentsRemoving;
var componentsRemovedSubject = (Subject<int[]>) _entity.ComponentsRemoved;
componentsAddedSubject.OnNext(_componentsAdded.ToArray());
var removalArray = _componentsRemoved.ToArray();
componentsRemovingSubject.OnNext(removalArray);
for (var i = 0; i < removalArray.Length; i++)
{
var componentTypeId = _componentsRemoved[i];
var allocationIndex = _entity.InternalComponentAllocations[componentTypeId];
_entity.ComponentDatabase.Remove(componentTypeId, allocationIndex);
_entity.InternalComponentAllocations[componentTypeId] = Entity.NotAllocated;
}
componentsRemovedSubject.OnNext(removalArray);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment