invalid get index? Issues with array

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

I have a level consisting of different parts, the level moves to the left. If the first part reaches a certain position, it gets teleported back, would be simple enough but nothing works and i get an invalid get index… why? my arrays are all assigned, even worse, it deletes my arrays from the inspector when hit play.

extends Node2D

var position_cache : Vector2
export onready var levels = []

func _ready():
	position_cache = levels.size().position

func _process(delta):
	for i in levels:
		print("something happening here?");
		levels[i].position.x -= 200 * delta
	if position.x < -600:
		if levels.size() > 0:
			levels[0].position = position_cache
:bust_in_silhouette: Reply From: kbal

You’re using a for-each type loop, so “i” is actually the object, not the index. This might work:

for level in levels:
    level.position.x -= 200 * delta

Also, this looks off to me:

func _ready():
    position_cache = levels.size().position

Array.size() returns an integer. You can use back() to get the last array element, if that is what you wanted to do instead.