Okay so for a week I'm trying to get this problem solved. I have a navmesh agent and it has a nav obstacle in it too, so it enables/disables this component in such a way other agents in the scene don't push him around. When other agents that you controll reach its destination they become an obstacle and when I click with mouse somewhere in the scene, it goes to a navmesh agent and starts to move again.
But now I have the problem that when I click, it doesnt switch to navmesh agent if its far from the player/object, sometimes it just dies and does not switch at all. And all agents are controlled by you, there is no enemy here that follows you .
Here is the code :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class moveTest : MonoBehaviour {
NavMeshAgent navAgent;
NavMeshObstacle obstacle;
// Use this for initialization
void Start() {
navAgent = GetComponent<NavMeshAgent>();
obstacle = GetComponent<NavMeshObstacle>();
}
// Update is called once per frame
void Update() {
move();
Stopped();
}
void Stopped()
{
if (navAgent.remainingDistance <= navAgent.stoppingDistance)
{
obstacle.enabled = true;
navAgent.enabled = false;
}
}
void move()
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Input.GetMouseButtonDown(1))
{
obstacle.enabled = false;
navAgent.enabled = true;
if (Physics.Raycast(ray, out hit, 10000))
{
navAgent.destination = hit.point;
//navAgent.SetDestination(hit.point);
}
}
}
}