Array Problem

Will try my best to explain my problem…

I have several objects with the same script attached called “NODE”. I created an array in that script, ike this:

public class NODE : MonoBehaviour {

public int[ ] FaceSkinTileX = new int[6]; 

}

This array will handle 6 diferente values that will change from object to object. so i need every object to have their own array.

But every time i try to change those values within a specific object, every object will get same values for the array.

I’m changing those values by doing this:

Obj.GetComponent<NODE>().FaceSkinTileX *= something;*
What am i doing wrong?

It has more to do with how you create and initialize the arrays than how you change the values. If you’re not intentionally creating/instantiating those arrays anywhere in code, are you perhaps instantiating the object that holds the array? If so, then the clone is probably pointing to the same array in memory when it’s created, and you should probably initialize them in Awake().

1 Like

Correct. “i” will go from 0 to 5

Yep, so your code is working exactly as written. That’s what a for loop does: “For every value from 0 to 5, do this thing”. So it will happen to every element in the array. If you just want to access a single element of the array, don’t use a for loop. Just access it by index directly. For example, to set the third element in the array (index 2):

myArray[2] = something;

Maybe i explain myself in the wrong way. The problem is that if i change index 2 to be equal to “something” then every array in my object collection will change to that value at index 2!

It sounds like you might have multiple references to the same array, instead of different arrays.

Each array needs to be created with new int or Array.Copy. If you assign the array simply like myArray = someOtherArray, then you haven’t created a new array, you’ve just created a new reference to the same array.

1 Like

I just rebuilt my code and now its working. I had an update to the last array that was passing its values to all the others… so dumb…

anyway, thank you both