Course contentsShow
← Unity Game Development
Lesson 542 of 8288. Artificial IntelligenceFree lesson

Developing Spatial Memory Systems

Learners will build a data structure to store the last known coordinates of a target, enabling AI to investigate lost sightings.

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:

  1. Active Pursuit: While the target is visible, continuously call UpdateMemory() with the target's current position.
  2. Transition Trigger: When the LineOfSight condition fails, do not clear the memory immediately. Instead, trigger an InvestigateState.
  3. Investigation: In the InvestigateState, command the NavMeshAgent to move to the LastKnownPosition.
  4. Completion: Once the agent reaches that coordinate and fails to find the target, call ClearMemory() to transition the AI back to its Idle or Patrol state.

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.