Combat & AI
This page covers health, attacking, and the simple enemy AI included in the template.
Health (Damageable)
Damageable is the base for units and buildings.
Key responsibilities:
- Hold maxHealth and currentHealth
- Provide TakeDamage(int)
- Raise events:
- OnHealthChanged(int current, int max)
- OnDied(Damageable self)
World-space health bars and the bottom info panel subscribe to these events to stay in sync with the actual health of the object.
Attacking (Attacker)
Attacker is a component usually attached to a Unit.
Typical fields:
- damage
- attackRange
- attackCooldown
- rotateTowardsTarget
Behavior:
- Holds a reference to a Damageable target.
- On each Update:
- If target is null or dead → clear target.
- If target is out of range → do nothing (movement scripts handle moving into range).
- If target is in range and cooldown is ready:
- Deal damage via target.TakeDamage(damage).
Attacker does not decide whom to attack; it only executes attacks on its current target.
Target assignment is done by player commands or AI scripts.
Player commands
UnitSelectionController manages:
- Left click & drag selection
- Right-click commands
Right-click behavior:
- Cast a ray from the mouse position.
- If it hits a Damageable on an attackable layer:
- Treat it as an attack command:
- Set the target on each selected unit's Attacker.
- Call MoveTo with a stopping distance based on attackRange.
- If it hits only the ground:
- Treat it as a move command:
- Call MoveTo on all selected units.
Enemy AI
The template includes a minimal enemy AI implementation.
EnemySpawnerBuilding
Attached to an enemy base building.
Fields:
- UnitType unitType to spawn
- float spawnInterval
- int maxAliveUnits
- Transform spawnPoint
- float spawnRadius
Behavior:
- Every spawnInterval seconds:
- Clean up the list of spawned units (remove dead references)
- If current count < maxAliveUnits:
- Spawn a new enemy unit near the spawn point.
EnemyUnitAI
Attached to each enemy unit (in addition to Unit and Attacker).
Fields:
- detectionRadius
- LayerMask playerTargetsMask
- scanInterval
- Optional leash settings
Behavior:
- Periodically scans for player targets (units / buildings) within detectionRadius using Physics.OverlapSphere.
- Picks the closest valid Damageable as target.
- Calls Attacker.SetTarget(target) and Unit.MoveTo(target.position, stoppingDistance).
- Optionally stops chasing if too far from its spawn position (leash).