简体   繁体   中英

Unity 3D C# Check for Vector3 in List

I'm using Argon Granberg's A* Pathfinding scripts and I'm trying to check if a list element is defined

There is a list of Vector3 values stored as p.vectorPath variable. I'm trying to test if list elements are defined with

if ( p.vectorPath[myIndex] != null ) {
...

But I'm getting the error in Unity that testing a Vector3 != null will always = true. So how can i test if this particular list index is defined?

Thanks.

Vector3 is a value type ( struct ) and there is no such thing as an undefined (or null) value type (except if you make it nullable). Value types are initialized in the moment they are declared in c# - if you didn't provide an initial value, it has its default value ( Vector3.zero in this case)

OTOH, if what you want is to know if the list has any element at the position N , you could just check if list.Count is greater than N

As with the other answer Vector3 cannot be null as it is a value type. You could declare the list with a Nullable type of Vector3 like this;

public class Foo
{
    public List<Vector3?> VectorPath;
}

Foo p = new Foo();

//...stuff...

if (p.VectorPath[someIndex].HasValue)
{
    //Do things.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM