0 votes

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
in Engine by (33 points)

1 Answer

+1 vote
Best answer

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.

by (18,211 points)
selected by

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

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.

Categories