- Home /
Reading reference variable alters said reference variable
So here's the method:
public Act[] Orientate(ActionType type, ActionDirection direction)
{
Act[] orientatedAct = referenceActions[(int)type].acts;
foreach (Act _act in orientatedAct)
{
Vector2 rotatedOrigin = new Vector2(_act.origin.x, _act.origin.y);
if (_act.origin.x > -2)
rotatedOrigin = Quaternion.Euler(0, 0, (90 * -(int)direction)) * new Vector2(_act.origin.x, _act.origin.y);
Vector2 rotatedDirection = Quaternion.Euler(0, 0, (90 * -(int)direction)) * new Vector2(_act.direction.x, _act.direction.y);
_act.origin = new Vector2Int(Mathf.RoundToInt(rotatedOrigin.x), Mathf.RoundToInt(rotatedOrigin.y));
_act.direction = new Vector2Int(Mathf.RoundToInt(rotatedDirection.x), Mathf.RoundToInt(rotatedDirection.y));
}
return orientatedAct;
}
...and for some reason of another, each time I call it, it alters a value within the referenceActions array. referenceActions is a serialized array used for me to define what the actions are. I don't reference referenceActions anywhere else, so I'm stumped as to why it's being changed. It seems to apply the rotation to referenceActions[(int)type].acts[0].direction
.
Any help is appreciated. Happy to provide more details.
Answer by Cornelis-de-Jager · Feb 26, 2020 at 06:29 AM
So what is happening is --> you are creating a new variable, BUT, you are assigning the new variable to the same memory location as the old one. Meaning when you do this:
Act[] orientatedAct = referenceActions[(int)type].acts;
they are actually sharing memory locations even if they are not the same variable. For example look at the following little program (you can test in https://dotnetfiddle.net/):
public static void Main()
{
int[] test = new int[]{ 1, 2, 3};
int[] test2 = test;
test2[0] = 5;
foreach (var item in test)
Console.WriteLine(item);
//Output --> 5
//Output --> 2
//Output --> 3
}
And that is what is happening to yours. To overcome this you need to create a variable with its own memory space. This can be easily done throught the Clone function:
Act[] orientatedAct = (Act[]) referenceActions[(int)type].acts.Clone();
Hope this helped.