How to make a for loop only on the first 2 value of a PoolVector2Array

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

Hi, if I have a PoolVector2Array and I only want a for loop using the first 2 vector setting. How could I code that. For example, I have many spawn positions in a PoolVector2Array, and I want different enemy be spawn at different position. However, the array[0,1] is not recognised by the editor, if some one could show what the right expression is, that would be helpful, thank you.

var enemyPosition =PoolVector2Array( [ Vector2(364,-496), Vector2(627, -496), Vector2(627,-353)])
func set_spawn_enemy (spawnPosition, spawnType):
 	for i in (spawnPosition):
		var enemy
		enemy = (spawnType).instance()
        enemy.position = i
func _on_Hotspot_body_entered(body):
    	if == "Player":
    		set_spawn_enemy(enemyPosition[0,1],  enemyTypeA)
:bust_in_silhouette: Reply From: exuin

This is because you’re trying to use the [0, 1] array in order to access something from the array enemyPosition instead of passing the array by itself in as an argument. Try set_spawn_enemy([0,1], enemyTypeA) instead.

Edit: This also means that you must access enemyPosition inside the set_spawn_enemy function as well since you’re not passing it as an argument. So either you change the assignment line to enemy.position = enemyPosition[i] or you change the function call to something like set_spawn_enemy([enemyPosition[0], enemyPosition[1]], enemyTypeA). It’s not possible to slice PoolVector2Arrays.

Thanks for answering my question, I have tried your suggestion but only [0,1] without an array name, the code is not working. I have tried a few approaches and finally made it work.

Idleman | 2021-01-14 06:33

Sorry, I should have been more clear with my initial answer. There’s no easy was to access a set of values from a PoolVector2Array, since you can’t slice the array with another array.

exuin | 2021-01-14 06:35

Thanks for the updated answer.

Idleman | 2021-01-14 06:49

:bust_in_silhouette: Reply From: Idleman

I have tried a few things and finally managed to make it work with

set_spawn_enemy([enemyPosition[0],enemyPosition[1]],  enemyTypeA)

that way, the enemy is spawned in the first 2 positions in an array.