Yultek / FRENS-Project

NPC Character Development
MIT License
3 stars 1 forks source link

NavMeshAgent Destination is set via code #1

Open gm3 opened 1 year ago

gm3 commented 1 year ago

Typically the NavMeshAgent destination is set via code like this:

using UnityEngine;
using UnityEngine.AI;

public class NavMeshDestinationUpdater : MonoBehaviour
{
    private NavMeshAgent agent;

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

    public void SetDestination(Transform destination)
    {
        agent.SetDestination(destination.position);
    }
}
gm3 commented 1 year ago
gm3 commented 1 year ago

To call SetDestination(Transform destination) from another script you would pass it a destination transform liek this:

public class OtherScript : MonoBehaviour
{
    public NavMeshAgent agentToControl;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out RaycastHit hit))
            {
                agentToControl.SetDestination(hit.point);
            }
        }
    }
}

This would let the use click a point and then it would update the Transform of the destination of the NavMeshAgent

To Implement:

By meeting these requirements, you should be able to use the OtherScript class to control the destination of the assigned NavMeshAgent based on mouse clicks.