+4 votes

I have var arr = Array()
How can I iterate all objects of this array with access to their funcs?

in Engine by (22 points)

3 Answers

+11 votes

I can't test it right now but I guess it's something like

var arr = Array()
# populate the array
for item in arr:
by (703 points)

Or this if you need the index:

for i in range(0, arr.size():
    print("Accessing item at index " + str(i))
0 votes

You can iterate over arrays with a for loop: http://docs.godotengine.org/en/latest/reference/gdscript.html#for
You can't store functions in variables or arrays in GD script but you can reference them:

# Call a function by name in one step
mynode.call("myfunction", args)

# Store a function reference
var myfunc = funcref(mynode, "myfunction")
# Call stored function reference
by (16 points)
0 votes

First, note that you can build your array using the Inspector:

export var arr = ["obj_1", "obj_2"]

You'll be able to change the variable type in the inspector.

Then, you will have to loop in your array using while or for.

#loop in arr
var i = 0
while i < arr.size():
    #Access func

    #Acces or change var
    arr[i].var_name = 1

    #Then iterate to avoid infinite loop!!
  1. First be sure they all have the same scripts, or at least the same func name!
  2. Looping in large array and accessing their funcs can get your game laggy
  3. Avoid death loops! (Always add i+=1 in the loop)
by (46 points)
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 Frequently asked questions and 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 [email protected] with your username.