In a 2D array of objects, whenever I modify a single value in the array, all values are also then modified in the same way. I have been struggling with this same problem for a while now and am looking for an explanation as to why things are behaving this way.
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Text;
public class C_Generate_Level : MonoBehaviour {
//enum Cardinal {Top, Right, Bottom, Left};
T[,] InitializeArray<T>(int height, int width) where T : new()
{
T[,] array = new T[height, width];
for (int i = 0; i < height; ++i)
{
for (int g = 0; g < width; ++g)
{
array[i, g] = new T();
}
}
return array;
}
class example
{
public void initialize_order ()
{
first = 1;
second = 2;
}
public void get_order ()
{
print (first + " " + second);
}
public void reverse_order ()
{
int hold;
hold = first;
first = second;
second = hold;
}
int first;
int second;
}
void Start ()
{
const int DIMENSIONS = 2;
int xCounter;
int yCounter;
int display_counter = 1;
example[,] exampleAry = InitializeArray<example>(DIMENSIONS, DIMENSIONS);
example template = new example ();
template.initialize_order ();
for (yCounter = 0; yCounter < DIMENSIONS; yCounter++)
{
for (xCounter = 0; xCounter < DIMENSIONS; xCounter++)
{
exampleAry[yCounter, xCounter] = template;
}
}
for (yCounter = 0; yCounter < DIMENSIONS; yCounter++)
{
for (xCounter = 0; xCounter < DIMENSIONS; xCounter++)
{
print (display_counter);
exampleAry[0,0].get_order();
exampleAry[0,1].get_order();
exampleAry[1,0].get_order();
exampleAry[1,1].get_order();
if (1 == xCounter && 0 == yCounter)
{ /////
exampleAry[yCounter, xCounter].reverse_order(); //This line is what confuses me: it performs reverse_order on every value in exampleAry, instead of only the current value
} /////
print (" ");
display_counter++;
}
}
print (display_counter);
exampleAry[0,0].get_order();
exampleAry[0,1].get_order();
exampleAry[1,0].get_order();
exampleAry[1,1].get_order();
return;
}
The output is as follows:
1
1 2
1 2
1 2
1 2
2
1 2
1 2
1 2
1 2
3
2 1
2 1
2 1
2 1
4
2 1
2 1
2 1
2 1
5
2 1
2 1
2 1
2 1