Open gm3 opened 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:
NavMeshAgent Reference: You need to assign a valid NavMeshAgent component to the agentToControl field in the Inspector of the GameObject that has the OtherScript component attached. Without a valid reference to a NavMeshAgent, calling SetDestination will result in an error.
Mouse Input: The script relies on detecting a left mouse button click (Input.GetMouseButtonDown(0)) to trigger the setting of the destination. Ensure that your mouse input is correctly registered and the left mouse button is properly mapped to Input.GetMouseButtonDown(0).
Camera Setup: The script uses Camera.main to get the main camera for the raycasting. Make sure you have a valid camera tagged as "MainCamera" in your scene.
Physics.Raycast: The script performs a raycast from the mouse position using Physics.Raycast. Ensure that your scene has colliders on the appropriate objects, and the raycast can successfully hit them to obtain the destination position.
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.
Typically the NavMeshAgent destination is set via code like this: