How to set AIDestinationSetter target through code


#1

Hi Everyone,

So i’m using the building AIPath to move to a target and it works just fine if i set the target manually through the Unity interface. However, i’m struggling with how to set the target via code.

What i have so far is when i click the left mouse button a function runs that sets the target for my Hero object. Using this target variable i can shoot at it. But i can’t figure out how to path to it also.

Any help is appreciated.


#2

Hi

You can either set the destination property of the AIPath script (also exists on all other movement scripts):
If you do this however, make sure that you remove the AIDestinationSetter, otherwise that will override the destination every frame.

var ai = GetComponent<AIPath>();
ai.destination = new Vector3(1,2,3);

or you can set the target transform on the AIDestinationSetter component

var aiDestSetter = GetComponent<AIDestinationSetter>();
aiDestSetter.target = someObject.transform;

#3

Thank you for the reply, i was very close to that.

The issue i’m running to (now and before) is it is telling me that AIDestinationSetter could not be found. What is causing that?


#4

Perhaps you are not including the Pathfinding namespace?
Make sure you have

using Pathfinding;

at the top of your script.


#5

YES!!! That did it! i’m still a newbie so didn’t realize it needed to be added. Thanks!


#6

Ok, now i’m getting a null reference error (which is ironic since the line giving the error is behind an IF statements checking make sure the value isn’t null). As best i can tell it is saying the variable aiDestSetter has no value.

Here is my code:

void Update () {
    
    if (target == null && Input.GetMouseButtonDown(0))
    {
        UpdateTarget();
    }

    //If target exists and is within range/LOS cast a fireball. Then reset cooldown.
    if (target != null && Input.GetMouseButtonDown(1))
    {
        Casting();
    }

    if (target != null)
    {
        Debug.Log("Target is " + target.name);
        var aiDestSetter = GetComponent<AIDestinationSetter>();
        aiDestSetter.target = target;
        Debug.Log("Target is " + aiDestSetter.target.name);
    }

}

Thank you again for your help, i really appreciate it.


#7

Hi

Yes, I would guess that you do not have an AIDestinationSetter component attached to the object.