0 votes
var gridSize = Vector2( 5,5);
var gridArray = []

func  _ready( ):
    for x in range(gridSize.x):
            for y in range(gridSize.y):

func _physics_process(delta):

func check_food_pos2():
        var emptyTiles = gridArray
        for tail in tailNodeArray:

        var pos = emptyTiles[randi()%emptyTiles.size()]

        food.position = grid2pix(pos);

I am trying to understand why my array (gridArray) changes its value in print. It should be constant after its first time. However it changes its value to emptyTiles. What do you think causing this and how should i prevent it?

in Engine by (35 points)

1 Answer

+1 vote
Best answer

Arrays are passed by reference. So when you do var emptyTiles = gridArray both variables are pointing at the same array object.

If you want to modify emptyTiles without touching gridArray use duplicate()

var emptyTiles = gridArray.duplicate()

See https://docs.godotengine.org/en/latest/classes/class_array.html#class-array-method-duplicate for more information.

by (20,675 points)
selected by

Thank you for the answer..It works now.

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.