Can't Get My Navmeshagents to Move to Different Directions.

I have several Navmeshagents and I want to move them to different locations at the same time. Here is my code. When I “right click” my mouse, they all move to the same location.

private NavMeshAgent agent;

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

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

I’ve been working on this for some time and can’t quite figure out how to move them separately.

You should use RaycastHit.collider.GetComponent to get the script on the agent that was hit, and use that with agent.SetDestination (hit.point). Also, make a manager object and put this script on the manager, and remove it from all the agents, since it’s wasteful to have many instances of the script doing exactly the same thing in Update.

This code makes all agents it’s attached to move to the hit point. You need to define conditions that decide if an individual agent should move or not. Assuming you are trying to create a basic RTS game, you would need a bool indicating if an agent is selected. This bool would need to be set e. g. through a selection manager. For example, it could set troops as selected if the left mouse button is clicked and a mouse raycast hit a collider that is attached to an agent’s GameObject.