racz16
racz16

Reputation: 721

Unity NavMesh Obstacle

I try to create an RTS game in Unity and I have a problem with path-finding. I use NavMesh for path-finding and it works well: units avoid static objects. But units don't avoid each other. There is a component called NavMesh Obstacle to units can avoid non-static objects but as I can see it doesn't work with NavMesh Agent because units try to avoid itself. So how can units avoid each other?

Upvotes: 4

Views: 6577

Answers (2)

Aernarion
Aernarion

Reputation: 248

I know it has been a while, but I have been facing the same issue for the last couple of hours. I finally managed to mix both components (NavMeshAgent and NavMeshObstacle). The only requirement is that they can't be enabled at the same time. My strategy was to have the agents disabled and the obstacles enabled (with the carve option enabled) and when I am moving an unit, disable the obstacle and enable the agent.

Just a last comment. I found that disabling the obstacle and enabling the agent in the same frame was causing a small unit displacement issue, so I had to use a coroutine to do that:

public IEnumerator EnableUnitMovementCoroutine()
{
    if (obstacle != null && obstacle.enabled)
    {
        obstacle.enabled = false;
    }

    yield return new WaitForEndOfFrame();

    if (agent != null && !agent.enabled)
    {
        agent.enabled = true;
        destinationSet = false;
    }

    yield return new WaitForEndOfFrame();

    unitMoving = true;
}

After this, just use the agent methods to calculate the path. BTW, you can see the navmesh in real time, including the unit's obstacles, by selecting the Navigation tab while in play mode.

Hope this helps!

PS. I just remembered that I had an strange issue with this check:

_agent.pathStatus != NavMeshPathStatus.PathComplete

So I am not using it currently, since it is always true from the moment I set the desired destination. This must be a bug from using both components simultaneously. I have replaced it for a remaining distance check.

Upvotes: 4

Tim van der Heijden
Tim van der Heijden

Reputation: 16

A NavMeshAgent already has a radius that is used to avoid other agents. You could try increasing this radius and see if that helps.

In addition, you can use the "avoidancePriority" variable to tweak the priority of agent to be avoided. You could make a script to change this value based on the amount of other agent around you.

That said, if you really need a good pathfinding system it is probably a better idea to get one at the asset store or make one yourself. My experience with Unity's pathfinding hasn't been very great because it tries to do too many things with too little freedom. For instance, it is (to my knowledge) not possible to have a NavMeshObstacle for a single NavMesh layer... meaning you can't really use them if you are using multiple layers for different units. (land/water/air/...)

Upvotes: 0

Related Questions