I want you to act as Senior Developer. I don't like this code, how it can be improved?…
- User
I want you to act as 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;
private AIDomainDefinition _domainDefinition; private Planner<AIContext> _planner; private Domain<AIContext> _domain; private AIContext _context; private SensorySystem _sensory; private AgentAccess _agentAccess; #pragma warning disable IDE0044 [MyBox.MustBeAssigned] [SerializeField] private GameObject _healthBar; #pragma warning restore IDE0044 private GameObject _healthBarInstance; private HealthSystem _healthSystem; private MemoryManager _memory; private AgentInventory _inventory; private AgentCharacteristics _characteristics; private AIPath _aIPath; private AgentPhysics _physics; public AIDestinationSetter AIDestinationSetter {get; private set; } [SerializeField] /// <summary> /// Object to move, talk or attack. /// </summary> public GameObject CurrentTargetToMove; public Transform AgentTransform { get; private set; } public Quaternion AgentRotation { get => _aIPath.rotation; set => _aIPath.rotation = value; } protected void Awake() { AIDestinationSetter = GetComponent<AIDestinationSetter>(); AgentTransform = transform; _aIPath = GetComponent<AIPath>(); _physics = GetComponent<AgentPhysics>(); _healthSystem = GetComponent<HealthSystemComponent>().GetHealthSystem(); _healthSystem.OnDead += SetDead; _memory = GetComponent<MemoryManager>(); _inventory = GetComponent<AgentInventory>(); _inventory.OnItemsUpdated += SetState; _inventory.ItemsInPickupRanger.CollectionChanged += OnListChanged; _characteristics = GetComponent<AgentCharacteristics>(); _characteristics.IsAlive = !_healthSystem.IsDead(); _domainDefinition = _characteristics.DomainDefinition; _agentAccess = new AgentAccess(this, _memory, _inventory); SetHTN(); SetDefaultWorldStates(); SpawnAndSetHealthBar(); _memory.WorldStates = _context.WorldState; } private void SetHTN() { if (_domainDefinition == null) { Debug.LogError($"Missing domain definition in {name}!"); return; } _planner = new Planner<AIContext>(); _context = new AIContext(_agentAccess, DebugContext); _sensory = new SensorySystem(this); _domain = _domainDefinition.Create(); } private void SetDefaultWorldStates() { _context.SetState(AIWorldState.CanMove, true, EffectType.Permanent); _context.SetState(AIWorldState.HasTargetToMove, false, EffectType.Permanent); _context.SetState(AIWorldState.IsInSafePlace, false, EffectType.Permanent); _context.SetState(AIWorldState.HasHumanInSensors, false, EffectType.Permanent); _context.SetState(AIWorldState.HasItemInPickupRanger, false, EffectType.Permanent); _context.SetState(AIWorldState.HasAmmoInWeapon, true, EffectType.Permanent); } private void OnListChanged(object sender, NotifyCollectionChangedEventArgs args) { _context.SetState(AIWorldState.HasItemInPickupRanger, _inventory.ItemsInPickupRanger.Count > 0, EffectType.Permanent); } public override void UpdateGObject() { if (_planner == null || _domain == null || _context == null) { Debug.LogError($"Missing HTN Element in {name}!"); return; } IfAgentAlive(); } private void IfAgentAlive() { if (!_characteristics.IsAlive) return; _context.Time = Time.time; _context.DeltaTime = Time.deltaTime; _sensory.Tick(_context); _planner.Tick(_domain, _context); UpdateHealthBarPosition(); DebugPlan(); } private void DebugPlan() { if (!DebugContext) return; foreach (var log in _context.MTRDebug) { Debug.Log(name +" " + log); } } private void SpawnAndSetHealthBar() { if (_healthBar == null) { Debug.LogError($"Missing health bar prefab in {name}!"); return; } var healthBarIns = Instantiate(_healthBar, transform); healthBarIns.GetComponentInChildren<HealthBarUI>().SetHealthSystem(_healthSystem); _healthBarInstance = new GameObject(name + " Health_Bar"); healthBarIns.gameObject.transform.SetParent(_healthBarInstance.transform, false); _healthBarInstance.transform.SetParent(transform.parent, false); } private void UpdateHealthBarPosition() { if (_healthBarInstance == null) return; _healthBarInstance.transform.position = transform.position; } private void SetState(AIWorldState state, bool value) { _context.SetState(state, value, EffectType.Permanent); } private void SetDead(object sender, System.EventArgs e) { _characteristics.IsAlive = false; _context.SetState(AIWorldState.CanMove, false, EffectType.Permanent); _aIPath.canMove = false; _physics.Collider.isTrigger = true; } public bool NeedsToBeSaved() { return true; } public bool NeedsReinstantiation() { return true; } public object SaveState() { SaveableEntity.Vector3Data targetPos; bool hasTarget; if (CurrentTargetToMove != null) { targetPos = new SaveableEntity.Vector3Data(CurrentTargetToMove.transform.position); hasTarget = true; } else { targetPos = new SaveableEntity.Vector3Data(); hasTarget = false; } return new NPCAgentData() { maxHealth = _healthSystem.GetHealthMax(), currentHealth = _healthSystem.GetHealth(), targetPosition = targetPos, hasTarget = hasTarget, isAlive = _characteristics.IsAlive, canMove = _aIPath.canMove, isTrigger = _physics.Collider.isTrigger, worldState = _context.WorldState, }; } public void LoadState(object state) { NPCAgentData data = (NPCAgentData)state; _healthSystem.SetHealthMax(data.maxHealth, false); _healthSystem.SetHealth(data.currentHealth); _characteristics.IsAlive = data.isAlive; _aIPath.canMove = data.canMove; _physics.Collider.isTrigger = data.isTrigger; } public void PostInstantiation(object state) { NPCAgentData data = (NPCAgentData)state; if (data.hasTarget) { CurrentTargetToMove = PoolSystem.Instance.PoolEmpty.Get(); CurrentTargetToMove.transform.position = data.targetPosition.ToVector3(); } _context.Reset(); _context.Init(); for (int i = 0; i < data.worldState.Length; i++) { _context.SetState((AIWorldState)i, data.worldState[i], EffectType.Permanent); } } public void GotAddedAsChild(GameObject obj, GameObject hisParent) { //throw new NotImplementedException(); } [System.Serializable] struct NPCAgentData { public float maxHealth; public float currentHealth; public bool hasTarget; public SaveableEntity.Vector3Data targetPosition; public bool isAlive; public bool canMove; public bool isTrigger; public byte[] worldState; } }}
- Assistant
To refactor this code, I would suggest applying the SOLID principles, as well as separating the concerns using the appropriate design patterns. Here's an overview of the modifications:
- Single Responsibility Principle: Break down the
NPCAgentclass into multiple classes or components, each with a single responsibility. - Open/Closed Principle: Use interfaces and abstract classes to implement a stable base and allow extension without modifying the base classes.
- Liskov Substitution Principle: Subtypes should be substitutable for their base types. Ensure the NPCAgent subtype does not violate the behavior of the base type.
- Interface Segregation Principle: Use smaller interfaces to define the required behavior for each class.
- Dependency Inversion Principle: Depend on abstractions instead of concretions.
Here's an example of some classes and interfaces we could introduce based on the current
NPCAgentcode:IAgent: Interface that exposes the necessary properties and methods for an agent.BaseAgent: An abstract class that implements the common functionality for agents. This should derive fromMonoBehaviourand the subclasses will inherit from it.NPCAgent: Inherits fromBaseAgentand adds NPC specific functionality.ISaveable: Interface for saving and loading agent state.IHealthSystem: Interface for handling agent health system logic.HealthSystemComponent: Class that handles agent health logic, implementingIHealthSystem.
The refactored
NPCAgentclass could look like this:public class NPCAgent : BaseAgent, ISaveable { // Keep only NPC-specific code here. // Move common/shared functionality to the BaseAgent class. // Implement ISaveable interface methods. }We'd move health system logic to the
HealthSystemComponent:public class HealthSystemComponent : MonoBehaviour, IHealthSystem { // HealthSystem component code here. }And we'd create a new
BaseAgentclass to contain common agent functionality:public abstract class BaseAgent : MonoBehaviour, IAgent { // Common agent properties and methods here. protected override void Awake() { // Common agent initialization code. // Calls to virtual methods for any subclass-specific initialization. } }By applying these principles, the code will become more modular, maintainable, and testable.
- Single Responsibility Principle: Break down the