I want to have a build mode where you can place buildings on a grid. Then you can press a Ready button to spawn enemy units that will use navmesh to find their way to a target position. But I don’t want players to be able to leave the build mode if there is no path available to the target position. So I want to calculate a path from spawn position to target position and if it is available, store the path, and flag a bool.
Outside of build mode, I want all units to use the same path that was already calculated. What I have so far almost does this. Using the CalculatePath() function however, returns true if just part of the path is available. I want it to only return true if a complete path is available. Otherwise you can leave build mode and the units end up only going part of the way.
As you can see, the enemy unit (Green capsule) finds the shortest path to the target position (Blue cube) and stops part way because there is no path from there to the target position. I dont want this. I want the path bool to only be true if the complete path is available, not just part of the path.
Here is the manager script I’m using to calculate the path.
using UnityEngine;
using System.Collections;
public class EnemyUnitManager : MonoBehaviour {
public NavMeshAgent spawnPosition;
Transform targetPosition;
[HideInInspector]
public bool pathAvailable;
public NavMeshPath navMeshPath;
void Start() {
navMeshPath = new NavMeshPath();
targetPosition = GameObject.FindGameObjectWithTag("Target").transform;
}
void Update() {
pathAvailable = spawnPosition.CalculatePath(targetPosition.position, navMeshPath);
}
}
And this is the script for the enemy unit.
using UnityEngine;
using System.Collections;
[RequireComponent (typeof(NavMeshAgent))]
public class Enemy : MonoBehaviour {
public EnemyUnitManager unitManager;
NavMeshAgent unit;
void Start () {
unit = transform.GetComponent<NavMeshAgent>();
}
void Update () {
if (Input.GetButtonDown("Jump")) {
if (unitManager.pathAvailable == false) {
Debug.Log("Path not available");
}
else {
unit.SetPath(unitManager.GetComponent<EnemyUnitManager>().navMeshPath);
}
}
}
}
I've been away from Unity for a while (got sucked into the Elite Dangerous time vacuum!) but I don't think navmesh can act as dynamically as that. However if you're doing something like an RTS and unit/building placement is on a grid as you've shown you could write your own to check the quickest path till it hits an object and then try alternate routes. Might a bit of a handful to program but a grid of locations shouldn't be too expensive computationally.
– Condyloma