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
Implementing a prioritization system for events in a decoupled architecture involves designing a mechanism that allows for flexible, configurable, and scalable event handling. Here's a step-by-step approach to achieve this:
1. Event Definition
Establish a unified event structure across the system. This can be a simple class or struct containing essential information:
csharp
public class AIEvent
{
public string EventType { get; set; } // e.g., "EnemySpotted", "HealthLow"
public int Priority { get; set; } // Priority level (higher = more urgent)
public objectEventData { get; set; } // Optional, additional data
}
2. Priority Levels
Define a set of priority levels. This can be an enum for simplicity or a more complex system if needed:
csharp
public enum PriorityLevel
{
Critical = 3,
High = 2,
Medium = 1,
Low = 0
}
3. Event Bus with Prioritization
Modify the event bus (or message bus) to handle prioritization. This can be achieved by using a priority queue (e.g., SortedSet<T> in C#) to store events before they are processed:
csharp
public class AIEventBus
{
private readonly SortedSet<(PriorityLevel, AIEvent)> _eventQueue =
new SortedSet<(PriorityLevel, AIEvent)>(
Comparer<(PriorityLevel, AIEvent)>.Create(
(x, y) => y.Item1.CompareTo(x.Item1) // Higher priority first
)
);
public void PublishEvent(AIEvent @event)
{
_eventQueue.Add((GetPriorityLevel(@event.EventType), @event));
}
public AIEvent ConsumeEvent()
{
if (_eventQueue.Count > 0)
{
var ( _, eventToConsume) = _eventQueue.Min;
_eventQueue.Remove(_eventQueue.Min);
return eventToConsume;
}
return null;
}
private PriorityLevel GetPriorityLevel(string eventType)
{
// Mapping of event types to priority levels, can be configurable
// For demonstration, a simple switch is used
return eventType switch
{
"EnemySpotted" => PriorityLevel.High,
"HealthLow" => PriorityLevel.Critical,
_ => PriorityLevel.Medium,
};
}
}
4. Decoupled Controllers with Event Handling
Ensure each controller listens to the event bus without knowing about other controllers. When an event is consumed, the responsible controller(s) will react accordingly:
csharp
public class EnemyDetectionController
{
public EnemyDetectionController(AIEventBus eventBus)
{
eventBus.EventConsumed += HandleEvent;
}
private void HandleEvent(AIEvent @event)
{
if (@event.EventType == "EnemySpotted")
{
// React to enemy spotted
}
}
}
public class HealthController
{
public HealthController(AIEventBus eventBus)
{
eventBus.EventConsumed += HandleEvent;
}
private void HandleEvent(AIEvent @event)
{
if (@event.EventType == "HealthLow")
{
// React to low health
}
}
}
5. Configuration and Flexibility
For enhanced flexibility, consider making the event to priority level mapping configurable (e.g., via a database, config file, or even a simple UI for designers). This allows for adjustments without code changes.
Dependency Injection: Controllers depend on the AIEventBus interface, not on each other.
Event-Driven Architecture: Communication is through events, not direct method calls.
Configurable Priority Mapping: Allows for changes in priority without altering code, reducing the need for tight coupling due to hard-coded priorities.