Practice of Unity automatic pathfinding technology

        When we create games, we often need to allow artificial intelligence such as characters and NPCs to navigate to designated target points autonomously. To achieve this function, Unity provides the NavMesh system. NavMesh is a triangular mesh that is used for automatic pathfinding of game objects, be they players, enemies, or other controllable objects.

        In this blog, we will introduce how to use Unity's NavMesh to find paths automatically, and provide a sample code for usage.

        First, we need to create the NavMesh. WindowOpen > AI> in the menu bar Navigation, which will open the Navigation window. In the Navigation window, we need to create a NavMesh for the terrain, buildings and other objects in the scene.

        In Navigationthe window, click Bakethe button to generate NavMesh, and Unity will scan the scene and build a triangular mesh of the walkable area. And all we have to do is add a NavMesh proxy component to the game object that needs automatic pathfinding.

        In this example, we create a C# script called AutoPathfinding. In this script, we define a public variable targetthat represents where we want to go. Then, in Start()the method , we get the NavMesh proxy component. In Update()the method , we check for the existence of the target variable and set the agent to move towards the target. Since NavMesh is built-in, no additional configuration is required.

Here is the sample code:

using UnityEngine;
using UnityEngine.AI;

public class AutoPathfinding : MonoBehaviour
{
    public Transform target; //目标位置,即要去往的地方

    private NavMeshAgent agent; //NavMesh代理

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

    void Update()
    {
        if (target != null) //如果目标存在
        {
            agent.SetDestination(target.position); //设置代理要去的位置
        }
    }
}

        Finally, we need to add the script to the game object that needs to find the path automatically, and specify the target variable in the Inspector toolbar.

        Summarize

        Through this blog, we have learned how to use Unity's NavMesh automatic pathfinding to achieve autonomous navigation of game objects. Remember to create a NavMesh and add the NavMesh proxy component to the game object before using it, and then just a few lines of code can make the game object automatically find its way to the specified position. Hope this blog can help your development!

Guess you like

Origin blog.csdn.net/Asklyw/article/details/130129833