private EntityComponent ValidateItem(int index, EntityComponent item, bool isReplacing) { if (item == null) { throw new ArgumentNullException(nameof(item), @"Cannot add a null component"); } var componentType = item.GetType(); var attributes = EntityComponentAttributes.Get(componentType); var onlySingleComponent = !attributes.AllowMultipleComponents; EntityComponent previousItem = null; for (int i = 0; i < Count; i++) { var existingItem = this[i]; if (index == i && isReplacing) { previousItem = existingItem; } else { if (ReferenceEquals(existingItem, item)) { throw new InvalidOperationException($"Cannot add a same component multiple times. Already set at index [{i}]"); } if (onlySingleComponent && componentType == existingItem.GetType()) { throw new InvalidOperationException($"Cannot add a component of type [{componentType}] multiple times"); } } } if (!AllowReplaceForeignEntity && entity != null && item.Entity != null) { throw new InvalidOperationException($"This component is already attached to entity [{item.Entity}] and cannot be attached to [{entity}]"); } if (entity != null) { var transform = item as TransformComponent; if (transform != null) { entity.TransformValue = transform; } else if (previousItem is TransformComponent) { // If previous item was a transform component but we are actually replacing it, we should entity.TransformValue = null; } item.Entity = entity; } return(previousItem); }
private static EntityComponentAttributes GetInternal([NotNull] Type type) { EntityComponentAttributes attributes; lock (ComponentAttributes) { if (!ComponentAttributes.TryGetValue(type, out attributes)) { attributes = new EntityComponentAttributes(type.GetTypeInfo().GetCustomAttribute <AllowMultipleComponentsAttribute>() != null); ComponentAttributes.Add(type, attributes); } } return(attributes); }