October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk7 min

Unity Unit Formations: Build Clear Slots and Reliable Movement

Create readable Unity unit formations by separating deterministic slot layouts from per-unit NavMeshAgent movement, then tune spacing, turns, and obstacle responses.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Readable Unity unit formations need two cooperating systems: code that gives each unit a distinct position in the formation, and movement that carries each unit to that position. A NavMeshAgent navigates for an individual character; it does not generate rows, grids, wedges, or other formation layouts. Compute one target slot per member, then let each agent move toward its own target.

Why units bunch together

If every unit follows the player’s position, every unit receives the same destination. An offset added to a shared target can become difficult to manage as the group turns, changes size, or moves around obstacles. The fix is not a single shared target: it is a distinct, stable slot for each member, calculated relative to a formation anchor such as the leader’s transform.

As an Amazon Associate I earn from qualifying purchases.

Unity describes NavMeshAgent as a component for mobile characters navigating a scene’s NavMesh. Its navigation references document individual agent movement and path controls, not a built-in formation generator. Shape generation and formation-level behaviours therefore belong in your project code. Unity’s NavMesh Agent manual and NavMeshAgent scripting reference describe the agent foundation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Separate slot layout from movement

Keep two questions separate: “Where should member i stand relative to the group?” and “How does this agent get there?” The layout function answers the first by producing a local-space offset. The movement component converts the resulting target into a destination request for that unit’s agent.

Use a formation anchor with a position and orientation. Generate offsets in the anchor’s local space, then transform them into world space. Deterministic indexing keeps the same member in the same slot while membership is unchanged, avoiding unnecessary reshuffling.

Build a simple row or grid first

A row is the easiest layout to inspect: each member gets a different position along the formation’s local X axis. A grid adds rows along local Z. This example keeps the leader outside the member list; the supplied list contains only the units receiving slots.

using UnityEngine;

public class FormationLayout : MonoBehaviour
{
    [SerializeField] private Transform anchor;
    [SerializeField] private Transform[] members;
    [SerializeField] private int columns = 3;
    [SerializeField] private float spacing = 1.5f;
    [SerializeField] private float rearOffset = 2f;

    public Vector3 GetSlotWorldPosition(int index)
    {
        int columnCount = Mathf.Max(1, columns);
        int row = index / columnCount;
        int column = index % columnCount;

        // Center each row around the anchor's local X axis.
        int membersInRow = Mathf.Min(columnCount, members.Length - row * columnCount);
        float centeredColumn = column - (membersInRow - 1) * 0.5f;
        Vector3 localOffset = new Vector3(
            centeredColumn * spacing,
            0f,
            -(rearOffset + row * spacing));

        return anchor.TransformPoint(localOffset);
    }

    private void Update()
    {
        for (int i = 0; i < members.Length; i++)
        {
            // The movement component receives the target separately.
            UnitSlotMover mover = members[i].GetComponent<UnitSlotMover>();
            if (mover != null)
                mover.SetSlotTarget(GetSlotWorldPosition(i));
        }
    }
}

The row-count calculation centers a partially filled final row as well as full rows. For a single row, set columns to at least the group size. For multiple rows, tune spacing and rearOffset to suit the units and camera. In a production controller, cache each unit’s mover instead of calling GetComponent on every update.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Give each unit its own destination

Each unit needs a movement component that receives the world-space slot target and requests navigation to it. The following version avoids requesting a new path when the target has barely changed. It also exposes path state for a debug display; a destination request is not proof that a complete route is already available.

using UnityEngine;
using UnityEngine.AI;

[RequireComponent(typeof(NavMeshAgent))]
public class UnitSlotMover : MonoBehaviour
{
    [SerializeField] private float retargetDistance = 0.25f;
    private NavMeshAgent agent;
    private Vector3 lastRequestedTarget;
    private bool hasTarget;

    public bool PathPending => agent != null && agent.pathPending;
    public NavMeshPathStatus PathStatus =>
        agent != null ? agent.pathStatus : NavMeshPathStatus.PathInvalid;

    private void Awake()
    {
        agent = GetComponent<NavMeshAgent>();
    }

    public void SetSlotTarget(Vector3 target)
    {
        if (agent == null || !agent.isOnNavMesh)
            return;

        if (hasTarget && (target - lastRequestedTarget).sqrMagnitude
            < retargetDistance * retargetDistance)
            return;

        if (agent.SetDestination(target))
        {
            lastRequestedTarget = target;
            hasTarget = true;
        }
    }
}

SetDestination triggers calculation of a new path, and Unity notes that the path may not be available until several frames later. Check pathPending while calculation is underway, then inspect pathStatus to determine whether the route is complete, partial, or invalid. See the SetDestination API reference and pathPending reference.

This example leaves a failed or unreachable destination decision to the project. A formation can keep a member’s last valid slot, seek a nearby reachable position, or allow the member to temporarily leave the formation. Check that targets lie on a traversable NavMesh area and that the agent’s area mask permits the route; Unity documents agent area masks and pathfinding settings in its NavMesh Agent manual.

Choose a shape for the camera and terrain

There is no universally best layout. A row is easy to read from the front but grows wide with more members. A grid balances width and depth, while a wedge emphasizes a forward direction but needs a deliberate index-to-slot mapping. A ring distributes units around an anchor but can be hard to read when the camera is low or the center is occupied.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Layout Silhouette and footprint Turn behaviour Obstacle and membership considerations
Row Clear front-facing line; width grows with member count. Rotates cleanly with the anchor, but a sharp turn swings the full line. Easy to index; adding a member changes row spacing if the row is re-centered.
Grid Compact, recognizable block; has both width and depth. Rotates as a block or can ease toward a new heading. Rows offer predictable reassignment; narrow passages may require compression or temporary shape changes.
Wedge Strong directional silhouette; footprint widens toward the rear. Reads naturally when aligned with travel, but can swing around the anchor during turns. Requires explicit assignment of members to left, center, and right positions; obstacle routing can distort its outline.
Ring Even distribution around the anchor; relatively wide footprint. Rotates with the anchor or can keep a world-facing orientation. New members may shift angular spacing; the center and nearby obstacles can make some slots unusable.

These are design trade-offs, not published Unity benchmarks. Decide how members are reassigned when units join, leave, or are destroyed; keeping assignments stable can prevent the entire group from changing targets after one membership change.

Handle turns, obstacles, and spacing

The ideal slot pattern and the agents’ actual positions will not always match during travel. Each agent follows its path and uses its own avoidance settings, so members may temporarily spread out, lag, or route around an obstacle. A formation is a target arrangement, not a guarantee that units remain in a perfect shape at every moment.

Pick a turn policy

  • Rotate immediately: slots follow the leader’s current orientation. This is responsive, but a fast turn can make members cross paths or chase sharply shifted targets.
  • Ease the heading: rotate the formation frame gradually. This softens target changes, at the cost of a slower response.
  • Relax and reform: allow members more freedom while turning or passing an obstacle, then guide them back to their slots. This prioritizes movement around the scene over a rigid silhouette.

These are project behaviours, not built-in Unity formation modes. Choose based on the camera’s readability, responsiveness, and how much temporary separation is acceptable.

Tune spacing against agent settings

Unity documents agent radius, height, avoidance, and pathfinding controls. If slot spacing is too tight relative to agent radii and avoidance behaviour, units may not settle into the intended pattern. Start with visible separation, then adjust the layout and agent settings together rather than assuming a mathematically precise grid will look precise in motion. The NavMesh Agent manual describes these controls.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Make targets visible while tuning

Draw a gizmo at each intended slot and a line from each unit to its current target. This distinguishes a layout error from a navigation delay or an unreachable destination. A small test scene with a baked NavMesh, a leader marker, a few units, and one obstacle is enough to inspect a stationary formation, movement, turns, and obstacle response. This is a suggested validation setup, not a performance test.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choose one owner for movement

For ordinary destination-based formation movement, let NavMeshAgent own path following, avoidance, and acceleration. Do not also move the same transform independently with a steering script, Animator root motion, or another controller unless you deliberately coordinate those systems.

Writing to NavMeshAgent.velocity is not a small adjustment to destination-driven movement: Unity says it overrides destination movement, collision avoidance, and acceleration control, while the agent remains constrained to the NavMesh. As Unity Technologies puts it in the Unity 6.0 velocity reference: “Setting the variable will override the simulation (including: moving towards destination, collision avoidance, and acceleration control) and command the NavMesh Agent to move using the specific velocity directly.” Unity’s component guidance also warns that competing movement controllers can create undefined behaviour or feedback problems.

Validate the formation in the Unity version you ship

  1. Prepare navigation: provide a usable baked NavMesh and confirm each agent is on it before sending destinations. Match the navigation setup and AI Navigation package to the Unity version used by your project; editor workflows and package details can vary by version.
  2. Inspect slots while stationary: display the anchor and gizmos for every generated target. Confirm that indices produce distinct, correctly oriented offsets.
  3. Move the leader gradually: verify that targets update at a deliberate cadence and that tiny frame-to-frame changes do not trigger needless path requests.
  4. Turn the leader: assess whether immediate rotation, eased rotation, or temporary relaxation best suits the game’s camera and movement.
  5. Add an obstacle: observe path state and actual spacing. Decide what a member should do if its assigned slot cannot be reached.

For broader background on navigation and grouped movement, Unity 2021 Cookbook, 4th Edition includes a chapter titled “Navigation Meshes and Agents,” with an example involving object-group movement through flocking. Flocking is related group movement, not a ready-made solution for assigning the stable slots described here.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.