Bool or int?

Some objects with some code I have made will have waypoints attached to themselves and some without. Those with waypoints should interact differently to those with, and to access these different functions, I hoped that the following if statement could work:

if (waypoints != null)
{
//Do stuff
}

The above does not work for my needs, as if a prefab has 0 waypoints set, they still technically aren’t null. Everything believes it has waypoints. To get around that, I tried the below:

if (waypoints.GetLength(0))
{
//Do stuff
}

Again, the above has not worked, as I am pulling an int where a bool is expected.

I tried to change the if statement, to look for whether a prefab has 0 waypoints, but trying to set an int where a bool is expected has caused even more problems.

I would appreciate some help on how to stop objects with 0 waypoints being able to call this, as it is a bool requirement and not an int requirement, I am not sure how to go about this.

Thanks.

If I understood this sentence correctly, you typed something like:

int numberOfWaypoints = ... //acquire number of waypoints

if (numberOfWaypoints = 0) // <-- missing == ?
{
     //Do stuff
}

If you just need to count how many Waypoint components a gameObject has, simply use:

int count = gameObject.GetComponents<Waypoint>().Length;
if (count == 0)
     return;

//Do stuff

If this doesn’t help, providing your Waypoint code might lead this forum post into right direction.

1 Like

If waypoints is an array you can use:

If(waypoints.Length > x) { }

Reply with some more info if this doesn’t help; i’m currently in an airport on my phone so can’t help that much :slight_smile:

1 Like

An array’s GetLength method gets the length in the specified dimension. So if you create a two-dimensional array:

string[,] arr = new string[5,7];
print(arr.GetLength(0)); //prints 5
print(arr.GetLength(1)); //prints 7
print(arr.GetLength(2)); //error

@Matt-Roper 's reply is probably the correct one. You could replace .Length with .GetLength(0) as they’re equivalent, but it’s really only common to use the GetLength method of getting an array’s length if the array has more than one dimension.

1 Like

Thanks for all of the feedback.

if (waypoints.Length = 0)
{
//Do stuff
}

Is the solution. Really appreciate the help.

Nope, the solution is :

if (waypoints.Length == 0) // missing ==
{
    //Do stuff
}
2 Likes