In this lesson, you will learn how to implement a spatial memory data structure that allows your AI to "remember" where it last saw a target, enabling it to investigate the area after losing line-of-sight.
The Concept of Spatial Memory
Until now, your NPCs have primarily relied on real-time data: if the player is in the FOV, chase; if not, idle. However, intelligent AI should exhibit "object permanence." When a player ducks behind a wall, the AI shouldn't immediately forget the player exists. Instead, it should store the Vector3 coordinates of the player’s last known position and navigate to that location to search.
Building the Memory Module
We can implement this by creating a simple SpatialMemory component. This script serves as a data container that updates whenever the AI's LineOfSight detection returns a valid position.
public class SpatialMemory : MonoBehaviour
{
public Vector3? LastKnownPosition { get; private set; }
public bool HasMemory => LastKnownPosition.HasValue;
public void UpdateMemory(Vector3 targetPosition)
{
LastKnownPosition = targetPosition;
}
public void ClearMemory()
{
LastKnownPosition = null;
}
}
Integration with State Logic
To make this work with your existing state machines, you need to bridge the gap between your Perception layer and your Navigation layer:
- Active Pursuit: While the target is visible, continuously call
UpdateMemory()with the target's current position. - Transition Trigger: When the
LineOfSightcondition fails, do not clear the memory immediately. Instead, trigger anInvestigateState. - Investigation: In the
InvestigateState, command theNavMeshAgentto move to theLastKnownPosition. - Completion: Once the agent reaches that coordinate and fails to find the target, call
ClearMemory()to transition the AI back to itsIdleorPatrolstate.
By decoupling the "sighting" from the "investigation," you prevent the AI from snapping back to inaction the moment the player breaks contact, creating a much more believable and persistent hunting behavior.
Key Takeaway: Spatial memory converts transient sensory input into persistent navigation goals, allowing AI to pursue targets even after direct visual contact is lost.