Store raycast into array

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

I want store my rayCast nodes into array but i get an error “Invalid set index ‘0’ (on base: ‘Array’) with value of type ‘RayCast’”
What i’m doing wrong?

var ray = []

func _ready():
	ray[0] = $RayLeftBack
	ray[1] = $RayRightFront
	ray[2] = $RayRightBack
	ray[3] = $RayLeftFront
:bust_in_silhouette: Reply From: kidscancode

You can think of an array as a “container” with a certain number of items in it. These items are numbered starting with 0. If the array has 3 things in it, for example, there is no item number 4.

What’s going wrong for you is that you’ve created a new empty array (no items) and are trying to assign something to a nonexistent position in the array, i.e. you can’t put something in position 0 when there is no position 0.

To add a new item to the array, expanding its size, you use append() like so:

var ray = []  # array is empty

func _ready():
    ray.append($RayLeftBack)  # ray now has one item
    ray.append($RayRightFront)  # ray now has two items
    # and so on

However, you can also populate the array at creation time:

onready var ray = [$RayLeftBack, $RayRightFront, $RayRightBack, $RayLeftFront]'

See the GDScript and Array documentation for more information. There is also this doc: GDScript: An introduction to dynamic languages which demonstrates techniques for working with arrays.

I have another question i want now to iterate this array using for loop but in one place i want to get the current loop’s index not my array value:

onready var ray = [$RayLeftBack, $RayRightFront, $RayRightBack, $RayLeftFront]
onready var wheel = [$vRearLeft, $vFrontRight, $vRearRight, $vFrontLeft]

this is my loop:

func springCalculation(dt):
	for i in ray:
		if i.is_colliding():
			var p = i.get_collision_point()
			wheel[i].translation = to_local(p)

the not working part is wheel[i] since i is my array value not a loop index

Huder | 2018-05-06 21:01