Why is my referenced variable changing values?
public Vector2[] touchOffsets;
private Vector2[] touchOffsetsScaled;
void OnEnable () {
touchOffsetsScaled = touchOffsets;
for ( int i=0; i<touchOffsets.Length; i++ ) {
touchOffsetsScaled[i] = new Vector2( touchOffsets[i].x * touchScale.x, touchOffsets[i].y * touchScale.y );
}
}
The Inspector shows touchOffsets values I've inputed correctly, once I turn on the script touchOffsets is modified by touchScale. It's as if it's directly linked to touchOffsetsScaled instead of being just a reference.
Nowhere else in the script uses touchOffsets, only touchOffsetsScaled. If I comment out the line in the loop neither Offsets or Scaled get modified as expected. This has me entirely stumped as it's something simple, but unexpected.
Answer by Dave-Carlile · Sep 15, 2015 at 05:42 PM
Arrays are objects, so when you do touchOffsetsScaled = touchOffsets
you're not copying the array values, you're changing touchOffsetsScaled to the same reference as touchOffsets. If you think of them as pointers, they're now pointing to the same array. From this point it doesn't matter which one you change, both will contain the same values because they are both the same array.
Another way to think about it... if you pass an array to a function and inside that function you add items to the array, if you then iterate through the array after the function returns you'll see the new values. That's because you passed an array reference to the function.
This is the same thing - you're assigning the array reference to touchOffsetsScaled.
Your answer
Follow this Question
Related Questions
Why is refrence to parent variable not updating 1 Answer
Instatiated object not being referenced in Start function? 2 Answers
Getting Int value from script to other script 2 Answers
Instantiate a script into an instantiated prefab 3 Answers
Can't see a public variable on a overloaded Event Trigger script 2 Answers