Wandering AI Walking towards destinations outside the graph

Alright, so I’ve been trying to get a wander script to work the way I want for a while now and I’ve gotten desperate so I thought I’d seek some help.

Here’s the code I’m using, most of which is from the Wandering AI tutorial:

using UnityEngine;
using System.Collections;
using Pathfinding;

public class WanderRandom : MonoBehaviour
    public float radius = 20;

    IAstarAI ai;

    void Start()
        ai = GetComponent<IAstarAI>();

    Vector3 PickRandomPoint()
        var point = Random.insideUnitSphere * radius;
        var pointOnGraph = AstarPath.active.GetNearest(point, NNConstraint.Default);
        if (pointOnGraph.node == null) Debug.LogError("No valid point on a graph could be found");
        if(pointOnGraph.node.Walkable == false){
            print("NOT WALKABLE");
        var closestPointOnGraph = pointOnGraph.position;
        closestPointOnGraph.y = 0;
        closestPointOnGraph += ai.position;
        return closestPointOnGraph;

    void Update()
        // Update the destination of the AI if
        // the AI is not already calculating a path and
        // the ai has reached the end of the path or it has no path at all
        if (!ai.pathPending && (ai.reachedEndOfPath || !ai.hasPath))
            ai.destination = PickRandomPoint();
        Debug.DrawLine(transform.position, ai.destination, Color.magenta);

It works in that the AI picks random points and goes there, however when he picks a spot that he can’t reach (It’s not on the graph or is part of an obstacle), he still starts to walk to the spot until he can no longer walk, at which point he picks a new spot. The result is awkward, jerky movements. Ideally, I’d like the AI to detect whether or not the spot he picked is walkable BEFORE starting the path, and if it isn’t pick a new path. I tried to write a line that would check to see whether the spots he was picking were being considered walkable or not, but the console didn’t report anything when he picked a destination that was outside the graph.

If none of this is making sense, please let me know and I’ll definitely upload screenshots and/or a video to demonstrate what I mean.



Try using one of the other methods in the wandering AI tutorial. One definite drawback of method 1 is that it does not take into account if the destination is reachable or not. However there are other methods that do (e.g Method 4). Alternatively you could check if the point is reachable using PathUtilities.IsPathPossible.

[Edit] Wait. You are the same poster as the other thread (Tell seeker to wait until a possible path is calculated to start the path). You have the same error in your code as mentioned in that thread.