I Made a Simple 2D Pathfinding & Navigation Tool for Unity!
Tags: unity3d, tooling, gamedev, package
Published: 2024-04-06 17:16:32

Recently whilst I was busy working on a 2D game in Unity, I had to add the functionality to have an Enemy AI navigate up and down a predefined path. Rather than resorting to downloading a plugin or implementing a complex A* Pathfinding algorithm for a single enemy, I decided to create a simple tool that would allow me to draw my navigation path directly in the game scene! This path could then be assigned to an entity AI, enabling them to move randomly along the path without all of the complexities. I named this tool NavPath2D, and it’s available for free use. 😊

This tool works as a GUI-based tool that allows you to draw paths (that entities such as your AI should follow) directly in your Unity Editor scene. 

These paths can then be saved as prefabs and assigned to entities. These entities will then randomly select a path to move on, eliminating the need for complex A* pathfinding algorithms. 
So, if you are someone who needs a simple pathfinding solution for your 2D game (especially since Unity does not support NavMeshes for 2D), then this tool can help you by offering a straightforward alternative to more complex solutions. You also have the flexibility to expand upon the basic functionality, making it adaptable to various genres and project requirements. 

You can find the download link and information on my [GitHub repository](https://github.com/christinec-dev/NavPath2D).

_**Please note that this tool is meant for simple navigation, and it will not give you the uniqueness that you can achieve through the use of A* Pathfinding algorithms. There are plenty of tools out there, many paid and expensive, so this tool was made to be an easy and affordable solution to 2D navigation issues._

---

## Tool Features

* **GUI-based Path Creation:** You can draw paths directly in the Unity Editor scene, providing a visual and intuitive way to define movement paths for 2D entities. This feature allows for the creation of paths that can navigate around obstacles, follow specific routes, and more, offering flexibility in how paths are formed.

* **Multiple Path Selection:** Once paths are created, they can be saved as prefabs. This functionality facilitates easy reuse and assignment to different entities within the project. Additionally, entities can be assigned multiple paths, enabling them to randomly decide which path to follow, adding an element of unpredictability to their movement.

* **Entity Movement Along Paths:** AI Entities can be assigned paths, enabling them to move along the defined waypoints. This feature eliminates the need for complex A* pathfinding algorithms, simplifying path management for 2D games and making it easier to implement straightforward movement patterns.

* **Simplified Pathfinding for 2D:** This tool addresses the lack of a built-in NavMesh feature for 2D in Unity by offering a straightforward solution for pathfinding. It provides a simple yet effective way to manage entity movement in 2D environments.

* **Customizable and Expandable:** The tool is designed to be a simple solution for basic pathfinding needs but also allows for expansion and customization to fit more complex scenarios. You can add your movement customizability by defining more randomization in movement, animations, and more.

![NavPath2D](https://cdn-images-1.medium.com/max/3840/0*7WDxjQuKtk31X3ew)

![NavPath2D](https://cdn-images-1.medium.com/max/3840/0*ouxJVdfLd_dTQtRI)

![NavPath2D](https://cdn-images-1.medium.com/max/3840/0*vJ4EHaMpwGAx05Is)

---

## Usage Instructions

### Download and Import:

Download the NavPath2D package and import it into your Unity project.

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*8j-WhK1ms5giXOOh)

### Setup AI Entity:

Ensure you have an AI entity set up in your Unity project.

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*I4mp5fB1EQAMf2ep)

### Create Path GameObject:

In your game scene, add a new empty GameObject and rename it to something like “Path_01”.

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*uJAj8ZoXbl1J0Jj6)

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*CH3ArjEPPiCnIP-h)

### Add Path Script:

Attach the **Path.cs** script to this GameObject. This script (which can be found in the Scripts/NavPath2D folder) allows you to draw paths onto your scene via the PathEditor.cs (found in ssets/Editor/NavPath2D/) Editor script as it holds the Waypoints that we add.

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*DzAVEc7o45oi_Oq9)

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*amzvGq7J_JfTXmmT)

### Manage Waypoints:

With the GameObject selected, you can start adding, removing, and moving waypoints.

* To add a waypoint, SHIFT-click in the scene window.

* To move a waypoint, click on the waypoint gizmo in the scene window.

* To remove a waypoint, CTRL-click on the waypoint gizmo in the scene window.

* To add a waypoint to an existing waypoint, select it and SHIFT-click a new waypoint.

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*l4HbsG8NWUUsaKob)

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*KIezmqafTlF5yzeQ)

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*wLbNuYGfWwAIH49t)

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*4Osg_B23toqGGePE)

You can add multiple GameObjects with the Path.cs script added to it to create multiple paths.

### Save Path as Prefab:

Once you’re done creating paths, drag the GameObject into your directory to turn it into a Prefab. This allows you to assign it to your entity. You can remove this prefab from the scene hierarchy.

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*uWgDgOVO-VaBpqcy)

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*6DR4Y3Uvd8z0x1ai)

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*6XGCLPOb38z2uPEr)

### Assign Path to Entity:

Select your entity and attach the **Walker.cs** (which can be found in the Scripts/NavPath2D folder) script to it. This is a demo script which allows you to assign the path prefabs to your entity, enabling it to randomly move along the paths. You can expand this script to include logic for breaks within movement, animations, etc., or combine it with your existing scripts. In the script:

```csharp
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    
    public class RandomWalker : MonoBehaviour
    {
        private Path currentPath; // path it chooses to walk on
        private int currentWaypointIndex = -1; // waypoint index
        public float speed = 2f; //entity speed - how fast it will move
        public float waypointTolerance = 1f; //how close it stays to path - the lower this value, the more accurate it is (do not set to 0).
        public List<GameObject> pathPrefabs; //path options entity can select from 
        
        void Start()
        {
            // Randomly choose and instantiate a path from the path prefabs addded
            GameObject pathGO = Instantiate(pathPrefabs[Random.Range(0, pathPrefabs.Count)]);
            currentPath = pathGO.GetComponent<Path>();
        }
    
        void Update()
        {
            // Move entity randomly on the waypoints of chosen path
            if (currentPath.waypoints.Count == 0) return;
              if (currentWaypointIndex == -1 || Vector3.Distance(transform.position, currentPath.waypoints[currentWaypointIndex].position) < waypointTolerance)
              {
                  if (currentWaypointIndex == -1)
                  {
                      currentWaypointIndex = Random.Range(0, currentPath.waypoints.Count);
                  }
                  else
                  {
                      int nextWaypointIndex = currentPath.waypoints[currentWaypointIndex].GetRandomConnectedWaypointIndex(); // found in Waypoint.cs
                      if (nextWaypointIndex != -1) 
                      {
                          currentWaypointIndex = nextWaypointIndex;
                      }
                      else
                      {
                          currentWaypointIndex = Random.Range(0, currentPath.waypoints.Count);
                      }
                  }
              }
              Vector3 waypointPosition = currentPath.waypoints[currentWaypointIndex].position;
              transform.position = Vector3.MoveTowards(transform.position, waypointPosition, speed * Time.deltaTime);
          }
      }
    }
```

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*1qYD1yOLodE5rR5H)

### Add Paths to Entity:

Now add the path prefabs that you created to the waypoint list on the script attached to your Entity.

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*sjFNGBna6u7CGjxR)

### Run Your Scene:

Finally, run your scene. Your entity should now choose a path to move on and move between the waypoints. Remember, the lower the waypointTolerance variable value, the closer the entity will walk to the waypoint path.

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*9TBDjByuY_QhA6Rl)

![NavPath2D](https://cdn-images-1.medium.com/max/2000/0*4qyJtRF5iF2gLBca)

---

## Conclusion

This tool not only streamlines the process of defining movement paths for AI entities but also eliminates the need for over-the-top pathfinding algorithms, making it an efficient solution for basic 2D games. NavPath2D addresses the absence of a built-in 2D pathfinding system in Unity, offering a straightforward alternative for managing entity movement in 2D environments! ❤️