How to loop over an array and access array elements?

What is the proper way to loop over an array of elements and access each element within a for loop in Udon? If possible, please provide udon graph images for

  1. Setting up an array
  2. Iterating over the array
  3. Access each element of the array

And any other tips you might have!

Thanks

First you need to make an array, which is any variable followed by [], such as float[]. Then define the size of the array, let’s go with 8.
image
Next we need to make a for loop, which will loop through the body multiple times until it reaches the end. Let’s put it after a start event and make it end after 8 loops. Alternatively, you could get the length of the array and then plug that into the for loop, but currently there is a bug that will cause the for loop to not stop if it’s end is set to a variable.


To set variables within the array, we need a float[] set node. This node needs to know what array we are writing to, so use get variable to give it the array. Then plug in the index from the for loop, which will be whatever number the for loop is on. The first time it loops it will be 0, the second time 1, etc. until it is finished. Plugging that number into the array means you will be able to set the value of the array at that location.

In order to have something to fill the array with, I’m just going to make a random 0-100 range like so

And just to make sure it’s all working, let’s make a couple debug logs to see what it puts into each entry.

And after putting this on an object and pressing play, let’s see what it does

Perfect! Now let’s see how we can retrieve some of those numbers later. All we need is the Float[] Get node, where we plug in the Array, choose which index to retrieve from, and print it to a debug log. You could also use another for loop to retrieve the entire array all at once.

2 Likes

Since most other stuff is already covered by Phasedragon, I’ll just add how to instantiate an array with dynamic size and iterate over it. This example will just fill the array with random numbers and then iterate through it to log the contents each frame.

1 Like

Hi @Merlin, thanks for this somewhat complex example to feast upon. I am trying to figure out the function/need of the array constructor (Ctor) in the flow of the start function and how it plays into the Set Variable node. Might you elaborate on that a bit? Thank you

The array constructor creates an array with the specified size. You then set the floatArray to that new array. The initial contents of the floatArray is discarded since it’s just there to declare the variable. This is just so that you can create arrays with different size requirements.

The rough equivalent to C# would be floatArray = new float[ArraySize];

1 Like

Okay awesome, that’s what I figured! Great to have the explanation. Thank you :smile: