[SOLVED] Array Math Help

This is more of a Javascript question than Unity related, but how could I add each element in Array B to each element in Array A each time the object goes off screen (all elements in both arrays are integers)?

I know a way to do it, but it would require doing the math for each individual element (which will exceed 50), so that’s really inefficient! But here’s how I know to do it:

var arrayA = [0, 10, 20, 30, 50];  // Each element here should equal 190 after arrayB is added
var arrayB = [190, 180, 170, 160, 150];  // Add this to each element in arrayA

function OnBecameInvisible ()
{
     arrayA[0] = arrayA[0] + arrayB[0];
     arrayA[1] = arrayA[1] + arrayB[1];
     arrayA[2] = arrayA[2] + arrayB[2];
     // And so on...
}

I’m sure there is a much more efficient way to do this, I just can’t figure it out.

Any help would be greatly appreciated!

- Chris

Use the for operator.

for (int i = 0; i < arrayA.Length; i++) {
arrayA[i] = arrayA[i] + arrayB[i];
}
1 Like

Looping them is one way…

Are the values always the same?

Thanks! This works! :slight_smile:

The values never change, so kru’s method works. I just needed to get each element in arrayA to equal 190 each time the object goes off screen.

If the values never change, why compute them at OnBecameInvisible, and not just 1 time and keep them (is what I was getting at) :slight_smile:

Oh, I misunderstood your question then!

Since I’m adding arrayB to each element in arrayA, each element in arrayA does change. But I need to add that 190 each time the object goes off screen because I want the object to jump ahead of the player (arrayA in this example was the preset x positions and arrayB was the amount to add to the x position). And depending on the object’s x position, the amount to add is different. :slight_smile:

Cool, I did start to consider possibilities after I responded… I got it :slight_smile: Glad ya got it working.

1 Like