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
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