/// <summary> /// Creates a deep copy of the object, reusing the given object. /// </summary> /// <param name="into">The object to copy into.</param> /// <returns>The copy.</returns> public IEntityManager DeepCopy(IEntityManager into) { var copy = (EntityManager)(into ?? MemberwiseClone()); if (copy == into) { // Not a shallow copy, also copy fields. // Clone the id manager. copy._idManager = _idManager.DeepCopy(copy._idManager); // Clone system manager. copy.SystemManager = SystemManager.DeepCopy(copy.SystemManager); // Get a list of entities for re-use. var copyValues = new Stack <Entity>(copy._entityMap.Values); copy._entityMap.Clear(); // Copy actual entities over. foreach (var entity in _entityMap.Values) { Entity entityCopy; if (copyValues.Count > 0) { entityCopy = copyValues.Pop(); } else { entityCopy = new Entity(); } copy.AddEntityUnchecked(entity.DeepCopy(entityCopy)); } } else { // Copy of this instance, create new instances for reference // types. // Clone the id manager. copy._idManager = _idManager.DeepCopy(); // Clone system manager. copy.SystemManager = SystemManager.DeepCopy(); // Clone all entities. copy._entityMap = new Dictionary <int, Entity>(); foreach (var entity in _entityMap.Values) { copy.AddEntityUnchecked(entity.DeepCopy()); } } // Set the entity manager for the clone's system manager. copy.SystemManager.EntityManager = copy; return(copy); }