I want you to act as C# Senior Developer. I don't like this code, how it can be improved? Try to use SOLID principles and design patterns
The code:
using System;
using UnityEngine;
using FluidHTN;
using Pathfinding;
using CodeMonkey.HealthSystemCM;
using System.Collections.Specialized;
using SaveLoadSystem;
namespace src
{
[RequireComponent(typeof(MemoryManager), typeof(AgentInventory), typeof(SaveableEntity))]
public class NPCAgent : AUpdater, ISaveable
{
public bool DebugContext = false;
code
Assistant
User
How would you handle cross-controller communication (e.g., health changes affecting AI behavior) while maintaining loose coupling between components?
Assistant
User
How would you implement a prioritization system for events where certain AI reactions must override others, while avoiding tight coupling between controllers?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Implement NPC states (NormalState, DeadState, CombatState)
Observer Pattern:
Use events for health and inventory changes
Factory Pattern:
Create controllers through factory methods
Strategy Pattern:
Swappable AI profiles via ScriptableObjects
Improved Component Structure:
Move related functionality to separate components
Reduce MonoBehaviour dependencies
Decoupled Save/Load System:
Separate save/load responsibility to dedicated controller
Context Object:
csharp
public class NPCContext
{
public NPCStateMachine StateMachine { get; }
public IHealthController Health { get; }
public IInventoryController Inventory { get; }
public IMovementController Movement { get; }
public NPCContext(
NPCStateMachine stateMachine,
IHealthController health,
IInventoryController inventory,
IMovementController movement)
{
StateMachine = stateMachine;
Health = health;
Inventory = inventory;
Movement = movement;
}
}
Better Event Handling:
Proper unsubscribe from events
Clear separation of health/inventory events
Additional recommendations:
Create ScriptableObject-based configuration for:
AI domains
Movement parameters
Health settings
Implement a Service Locator pattern for cross-system communication
Use Unity's new Input System for better input handling
Consider using UniRx for reactive programming patterns
Add proper error handling and null checks
Implement pooling for health bars and other frequently created/destroyed objects
This structure improves maintainability, testability, and extensibility while keeping the codebase more organized. Each component can be developed and tested independently, and the NPC agent becomes more of a coordinator than a god-class.
Here are several effective approaches to handle cross-controller communication while maintaining loose coupling, ordered by increasing sophistication:
1. Observer Pattern with C# Events
Implementation:
csharp
// Health Controller
public class HealthController : IHealthController
{
public event Action<float> OnHealthChanged;
public event Action OnDeath;
private void UpdateHealth(float amount)
{
// ...
OnHealthChanged?.Invoke(currentHealth);
if(currentHealth <= 0) OnDeath?.Invoke();
}
}
// AI Controller
public class AIController : IAIController
{
public AIController(IHealthController health)
{
health.OnDeath += HandleDeath;
health.OnHealthChanged += HandleHealthChange;
}
private void HandleDeath()
{
// Transition to flee state or other behavior
}
private void HandleHealthChange(float health)
{
// Update threat assessment
}
}
2. Mediator Pattern with Shared Context
csharp
// Shared Mediator
public class NPCMediator
{
public event Action<NPCEvent> OnNPCEvent;
public void PublishEvent(NPCEventType type, object data = null)
{
OnNPCEvent?.Invoke(new NPCEvent(type, data));
}
}
// Event Types
public enum NPCEventType { Death, HealthChanged, InventoryUpdated }
public record NPCEvent(NPCEventType Type, object Data);
// In HealthController
_mediator.PublishEvent(NPCEventType.HealthChanged, new { CurrentHealth });
// In AIController
_mediator.OnNPCEvent += event =>
{
if(event.Type == NPCEventType.Death)
{
HandleDeathSequence();
}
};
3. Message Bus with ScriptableObjects (Unity-specific)
csharp
// ScriptableObject Event Channel
[CreateAssetMenu(menuName = "Events/NPC Event Channel")]
public class NPCEventChannel : ScriptableObject
{
public event Action<NPCEvent> OnEventRaised;
public void RaiseEvent(NPCEventType type, object data = null)
{
OnEventRaised?.Invoke(new NPCEvent(type, data));
}
}
// In HealthController
[SerializeField] private NPCEventChannel _eventChannel;
_eventChannel.RaiseEvent(NPCEventType.HealthChanged, currentHealth);
// In AIController
[SerializeField] private NPCEventChannel _eventChannel;
_eventChannel.OnEventRaised += HandleNPCEvent;
4. Reactive Programming with UniRx (Requires UniRx package)
csharp
// Health Controller
public class HealthController
{
public ReactiveProperty<float> CurrentHealth { get; } = new();
public ReactiveCommand OnDeath { get; } = new();
}
// AI Controller
public class AIController
{
public AIController(HealthController health)
{
health.CurrentHealth
.Subscribe(health => UpdateThreatAssessment(health))
.AddTo(disposables);
health.OnDeath
.Subscribe(_ => TransitionToDeadState())
.AddTo(disposables);
}
}
5. State Machine with Context Sharing
csharp
public class NPCStateMachine
{
private INPCState _currentState;
private NPCContext _context;
public void ChangeState(INPCState newState)
{
_currentState?.Exit();
_currentState = newState;
_currentState.Enter(_context);
}
}
public class HurtState : INPCState
{
public void Enter(NPCContext context)
{
context.Movement.SlowDown(0.5f);
context.AI.SetPriority(BehaviorPriority.SelfPreservation);
}
}
6. Service Locator Pattern
csharp
public static class ServiceLocator
{
private static readonly Dictionary<Type, object> _services = new();
public static void Register<T>(T service) => _services[typeof(T)] = service;
public static T Get<T>() => (T)_services[typeof(T)];
}
// During initialization
ServiceLocator.Register<IHealthEvents>(healthController);
// In AIController
var healthEvents = ServiceLocator.Get<IHealthEvents>();
healthEvents.OnLowHealth += HandleLowHealth;
Best Practice Recommendations:
Hybrid Approach: Combine ScriptableObject events for cross-system communication with direct interface-based communication within the same context
Layered Architecture:
Core Systems: Communicate through interfaces
Cross-cutting Concerns: Use global message bus
Gameplay Systems: Use ScriptableObject events
Dependency Management:
csharp
public class NPCContext
{
public IHealthController Health { get; }
public IAIController AI { get; }
public IMovementController Movement { get; }
public IInventoryController Inventory { get; }
public NPCContext(
IHealthController health,
IAIController ai,
IMovementController movement,
IInventoryController inventory)
{
Health = health;
AI = ai;
Movement = movement;
Inventory = inventory;
}
}
Event Lifecycle Management:
Always unsubscribe from events
Use weak references for critical systems
Implement event debugger tools
Unity-Specific Optimization:
csharp
// Event Channel with UnityEvent
public class GameEvent : ScriptableObject
{
private readonly List<GameEventListener> listeners = new();
public void Raise()
{
for(int i = listeners.Count - 1; i >= 0; i--)
listeners[i].OnEventRaised();
}
public void RegisterListener(GameEventListener listener) => listeners.Add(listener);
public void UnregisterListener(GameEventListener listener) => listeners.Remove(listener);
}
// Usage in Inspector
public class HealthController : MonoBehaviour
{
[SerializeField] private GameEvent deathEvent;
private void OnDeath()
{
deathEvent.Raise();
}
}
Choose the approach based on your project's complexity:
Small projects: C# events + interface-based communication
Medium projects: ScriptableObject event system
Large projects: Full message bus + state machine + reactive programming
Remember to always:
Use interfaces instead of concrete implementations
Limit direct controller-to-controller references
Centralize cross-system communication
Implement proper event unsubscription
Use debugging tools for event flow visualization
Here's an implementation using a prioritized event system with a hybrid approach combining the Command Pattern, Observer Pattern, and State Pattern, while maintaining loose coupling through a priority-based event bus:
csharp
// 1. Define Priority Event System
public enum AIEventPriority
{
Critical = 0, // Immediate danger (e.g., low health)
High = 1, // Combat engagement
Medium = 2, // Item collection
Low = 3 // Idle behavior
}
public struct AIEvent
{
public AIEventPriority Priority { get; }
public string EventType { get; }
public object Data { get; }
public CancellationTokenSource CancellationToken { get; }
public AIEvent(AIEventPriority priority, string type, object data = null)
{
Priority = priority;
EventType = type;
Data = data;
CancellationToken = new CancellationTokenSource();
}
}
// 2. Implement Priority Event Bus
public class AIEventBus
{
private readonly PriorityQueue<AIEvent, AIEventPriority> _eventQueue = new();
private readonly Dictionary<string, List<Action<AIEvent>>> _subscriptions = new();
public void Publish(AIEvent @event)
{
_eventQueue.Enqueue(@event, @event.Priority);
ProcessEvents();
}
public void Subscribe(string eventType, Action<AIEvent> handler)
{
if (!_subscriptions.ContainsKey(eventType))
_subscriptions[eventType] = new List<Action<AIEvent>>();
_subscriptions[eventType].Add(handler);
}
private async void ProcessEvents()
{
while (_eventQueue.Count > 0)
{
var currentEvent = _eventQueue.Dequeue();
if (_subscriptions.TryGetValue(currentEvent.EventType, out var handlers))
{
foreach (var handler in handlers.ToArray()) // Clone for safe iteration
{
if (currentEvent.CancellationToken.IsCancellationRequested)
break;
handler.Invoke(currentEvent);
}
}
}
}
}
// 3. State Controller with Priority Handling
public class AIStateController : MonoBehaviour
{
private AIEventBus _eventBus;
private AIBaseState _currentState;
private Dictionary<Type, AIBaseState> _states = new();
private void Awake()
{
_eventBus = ServiceLocator.Get<AIEventBus>();
// Initialize states
_states = new Dictionary<Type, AIBaseState>
{
[typeof(IdleState)] = new IdleState(),
[typeof(CombatState)] = new CombatState(),
[typeof(EmergencyState)] = new EmergencyState(),
[typeof(ItemCollectionState)] = new ItemCollectionState()
};
SubscribeToEvents();
}
private void SubscribeToEvents()
{
_eventBus.Subscribe("HealthCritical", HandleHealthEmergency);
_eventBus.Subscribe("EnemySpotted", HandleCombatStart);
_eventBus.Subscribe("ItemDetected", HandleItemCollection);
}
private void HandleHealthEmergency(AIEvent @event)
{
if (ShouldInterruptCurrentState(@event.Priority))
{
_currentState?.Exit();
_currentState = _states[typeof(EmergencyState)];
_currentState.Enter(@event);
}
}
private bool ShouldInterruptCurrentState(AIEventPriority incomingPriority)
{
return _currentState == null ||
incomingPriority < _currentState.CurrentPriority;
}
private void Update() => _currentState?.Tick();
}
// 4. State Base Class with Priority
public abstract class AIBaseState
{
public abstract AIEventPriority CurrentPriority { get; }
public abstract void Enter(AIEvent triggeringEvent);
public abstract void Tick();
public abstract void Exit();
}
// 5. Concrete State Implementation
public class EmergencyState : AIBaseState
{
public override AIEventPriority CurrentPriority => AIEventPriority.Critical;
private AIEvent _triggeringEvent;
public override void Enter(AIEvent triggeringEvent)
{
_triggeringEvent = triggeringEvent;
// Initiate emergency behavior
}
public override void Tick()
{
// Handle emergency state logic
}
public override void Exit()
{
// Clean up emergency state
}
}
// 6. Usage in Controllers
public class HealthController : MonoBehaviour
{
[SerializeField] private float _criticalHealthThreshold = 0.2f;
private AIEventBus _eventBus;
private void Awake() => _eventBus = ServiceLocator.Get<AIEventBus>();
private void Update()
{
if (GetHealthPercentage() < _criticalHealthThreshold)
{
_eventBus.Publish(new AIEvent(
AIEventPriority.Critical,
"HealthCritical",
new { CurrentHealth = GetHealthPercentage() }
));
}
}
}
public class PerceptionController : MonoBehaviour
{
private AIEventBus _eventBus;
private void Awake() => _eventBus = ServiceLocator.Get<AIEventBus>();
private void OnEnemyDetected(Enemy enemy)
{
_eventBus.Publish(new AIEvent(
AIEventPriority.High,
"EnemySpotted",
new { Enemy = enemy, Position = enemy.transform.position }
));
}
}
Key Features:
Priority-based Event Queue:
Events are processed in order of their priority
Higher priority events can cancel lower priority actions
Uses CancellationToken pattern for cooperative cancellation
Loose Coupling Architecture:
Controllers only interact with the event bus
No direct references between systems
State transitions handled through abstract states
Interruptible States:
States declare their current priority level
New events automatically interrupt lower-priority states
State cleanup handled through Exit() method
Event-driven Design:
Systems react to events rather than polling
Clear separation between event generation and handling
Easy to add new event types and handlers
Extensible State System:
New states can be added without modifying existing code
State priority is self-contained within each state
State transitions are managed through events
Advanced Features to Consider:
Event Preemption Rules:
csharp
public class AIEventBus
{
// Add to existing implementation
public void Publish(AIEvent @event)
{
// Cancel lower-priority events
foreach (var existingEvent in _eventQueue.UnorderedItems)
{
if (existingEvent.Priority > @event.Priority)
{
existingEvent.Element.CancellationToken.Cancel();
}
}
_eventQueue.Enqueue(@event, @event.Priority);
ProcessEvents();
}
}
State Transition History:
csharp
public class AIStateController
{
private Stack<AIBaseState> _stateHistory = new();
private void TransitionToState(Type newStateType, AIEvent @event)
{
if (_currentState != null)
{
_stateHistory.Push(_currentState);
_currentState.Exit();
}
_currentState = _states[newStateType];
_currentState.Enter(@event);
}
public void RevertToPreviousState()
{
if (_stateHistory.Count > 0)
{
_currentState?.Exit();
_currentState = _stateHistory.Pop();
_currentState.Enter(null);
}
}
}
Event Cooldown System:
csharp
public class AIEventBus
{
private Dictionary<string, float> _eventCooldowns = new();
public void Publish(AIEvent @event, float cooldown = 0f)
{
if (cooldown > 0 && _eventCooldowns.TryGetValue(@event.EventType, out var lastTime))
{
if (Time.time - lastTime < cooldown) return;
}
_eventCooldowns[@event.EventType] = Time.time;
// Rest of publish logic
}
}
Usage Flow:
Systems generate events with priorities
Event bus queues and sorts events
State controller evaluates event priority vs current state
High-priority events interrupt low-priority states
New state executes until completion or higher-priority interruption
On state exit, controller can resume previous state
This implementation provides a flexible, maintainable system that:
Enforces loose coupling through event-based communication
Allows natural prioritization of AI behaviors
Supports interruptions and resumptions of activities
Is easily extensible with new behaviors and event types
Maintains clean separation of concerns between systems
The pattern works particularly well for complex AI systems requiring: