- Home /
(Yet another) Accessing array in another script - ref or copy?
I know how to access an array from another script. I'm pretty sure I know the answer to this, but want to be sure: am I accessing a copy of that array, or a reference to it? What if that array is changed?
Ex (both scripts on same object):
class ClassA {
Color32[] colors;
void Start {
colors = new Colors32[640*480];
}
Update() {
// change colors
foreach (c in colors)
c = RandomColor();
// or REALLY change colors
colors = someTexture.GetPixels();
}
}
now in another class I want to get at the CURRENT 'colors' array.
class ClassB {
ClassA A; // will set with Inspector
void Update() {
Analyze (A.colors); // the CURRENT color array from object A
}
}
So, what will A.colors be in classB's Update? Ideally what I want is a reference to that array so I can read/write it, no matter what it happens to be, like a reference or C pointer-to-pointer.
Answer by Statement · Jan 21, 2012 at 12:48 AM
This code shouldn't do anything (at least not in C#), because c will become a temporary variable, so assigning a value to this temporary variable means it'll be lost.
foreach (c in colors)
c = RandomColor();
You are accessing a reference to the Color32 array. The contents are not copied by accessing it.
So, what will A.colors be in classB's Update?
A.colors will probably reference a new array each time as I suspect someTexture.GetPixels() return a new array each call. The copying doesn't happen when you access A.colors -- it'll just be a reference and the contents will be shared across different accesses. However, it's ClassA.Update that set a new reference to colors each update, and I am pretty sure each call to GetPixels generate a new array.
So the net effect is that you'll probably see different references each time you access ClassA.colors because it's reassigned every frame.
Thanks. Yeah that random things was more of an indication of setting values within an existing array, vs (as you correctly say) getting a whole new array via GetPixels.