/// <inheritdoc /> public void Load() { IEnumerable <TypeInfo> behaviors = ReflectionHelper.GetClassesAssignableFrom <IBehavior>(); foreach (var type in behaviors) { IEnumerable <BehaviorAttribute> behaviorAttributes = type.GetCustomAttributes <BehaviorAttribute>(); if (behaviorAttributes != null) { foreach (BehaviorAttribute attribute in behaviorAttributes) { if (!_behaviors.TryGetValue(attribute.Type, out IList <BehaviorEntryCache> behaviorsCache)) { behaviorsCache = new List <BehaviorEntryCache>(); _behaviors.TryAdd(attribute.Type, behaviorsCache); } if (attribute.IsDefault) { if (behaviorsCache.Any(x => x.IsDefault)) { throw new InvalidOperationException($"{attribute.Type} already has a default behavior."); } var entityBehavior = new BehaviorEntryCache(type, true); behaviorsCache.Add(entityBehavior); } else { if (behaviorsCache.Any(x => x.MoverId == attribute.MoverId)) { _logger.LogWarning($"Behavior for mover id {attribute.MoverId} and type {type} is already set."); continue; } var entityBehavior = new BehaviorEntryCache(type, false, attribute.MoverId); behaviorsCache.Add(entityBehavior); } } } } foreach (var behaviorsForType in _behaviors) { if (!behaviorsForType.Value.Any(x => x.IsDefault)) { throw new InvalidProgramException($"{behaviorsForType.Key}"); } } Count = _behaviors.Aggregate(0, (current, next) => current + next.Value.Count); _logger.LogInformation("-> {0} behaviors loaded.", Count); }
/// <inheritdoc /> public IBehavior GetDefaultBehavior(BehaviorType type, IWorldEntity entity) { BehaviorEntryCache behaviorEntry = GetBehaviorEntry(type, x => x.IsDefault); if (behaviorEntry == null) { throw new ArgumentNullException(nameof(behaviorEntry), $"Cannot find default behavior for type {type}."); } return(CreateBehaviorInstance(behaviorEntry, entity)); }
/// <summary> /// Creates a new behavior instance. /// </summary> /// <param name="behaviorEntry">Behavior entry informations.</param> /// <param name="entity">Entity.</param> /// <returns>Behavior.</returns> private IBehavior CreateBehaviorInstance(BehaviorEntryCache behaviorEntry, IWorldEntity entity) => ActivatorUtilities.CreateInstance(_serviceProvider, behaviorEntry.BehaviorTypeInfo, entity) as IBehavior;
/// <inheritdoc /> public IBehavior GetBehavior(BehaviorType type, IWorldEntity entity, int moverId) { BehaviorEntryCache behaviorEntry = GetBehaviorEntry(type, x => x.MoverId == moverId); return(behaviorEntry == null?GetDefaultBehavior(type, entity) : CreateBehaviorInstance(behaviorEntry, entity)); }