has() in a PoolVector2Array?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By sian2005

Hello,

In a normal Array, there is a fuction called has(), that checks if there is a value in the given array.

However, in the PoolVector2Array, I can’t find a function that does something like that.

Does anyone have an idea how to check for a value in a PoolVector2Array?

Kind Regards, sian2005

:bust_in_silhouette: Reply From: Zylann

You can try with this helper function:

static func poolvector_has(poolvector, value):
    for v in poolvector:
        if v == value:
            return true
    return false

if poolvector_has(your_vector, value):
    ...
:bust_in_silhouette: Reply From: Leirda

Hello,

Given the official documentation, there is no such method on PoolVector2Array.

However, in GDScript, you can type cast values using the as keyword :

var vector2_pool = PoolVector2Array([Vector2(0, 0), Vector2(1, 0)])

if vector2_pool.has(Vector2(0, 0)): # will throw error
    print("true")
if (vector2_pool as Array).has(Vector2(0, 0)): # properly print true
    print("true")

Please read more about static typing here.

Best regards, Leirda

Using as like this will duplicate the entire array just to call has.

Zylann | 2020-03-31 20:16

Beware of the performance implications this could have. While this is a valid solution, this could easily become a bottleneck if your array has more than a few dozen elements.

Calinou | 2020-04-01 08:28