5
votes

I have a scene in Unity where I am using Unity's navigation functionalities to calculate a path and have a NavMeshAgent to walk it. I must make slight modifications to the path then reassign it to the agent.

Now, Unity docs say clearly that NavMeshAgent.path can be set pragmatically (not read only).

See here: https://docs.unity3d.com/Documentation/ScriptReference/NavMeshAgent-path.html

So it's possible to create a new NavMeshPath and assign it to the NavMeshAgent.

Unfortunately for me, the NavMeshPath doesn't allow you to assign an array of Vector3 in any way as the corners property is Read Only. What the...

I need a workaround for this. Any help appreciated!

Thank you for your time.

1

1 Answers

3
votes

While you can't assign a new set of Vector3 to the NavMeshPath.corners, you can change a NavMeshPath's corners.

So instead of making your own, have the agent generate a path with the correct number of corners, then change those corners as you need to, then you can use that path in your NavMeshAgent.SetPath.

I am using this to force movement to be by squares, instead of as smooth as it wants to be.

Example

Vector3 vHit = WhereWeWantToGo;
var vNavMeshPath = new NavMeshPath();
mAgent.CalculatePath(vHit, vNavMeshPath);

for(var vIndex = 0;vIndex < vNavMeshPath.corners.Length;vIndex++){
    var vPoint = vNavMeshPath.corners[vIndex];
    vPoint.x = ChangeValue(vPoint.x);
    vPoint.y = ChangeValue(vPoint.y);
    vPoint.z = ChangeValue(vPoint.z);
}

mAgent.SetPath(vNavMeshPath);

It has to be a for loop it can't be a foreach.

Now, in order to be able to generate arbitrary NavMeshPaths with various number of corners. You could make an out of sight NavMesh area with a single agent with a set of points that will generate known numbers of corners, which you can then do whatever you want with.

The key being that you can't set the corners array, but you can muck with what's in it already.