public class TestClass
{
public int TestNumber;
public string TestName;
public TestClass(string name, int number)
{
TestName = name;
TestNumber = number;
}
}
public class AnotherClass
{
TestClass Var1, Var2;
void Start()
{
Var1 = new TestClass("Me", 1);
Var2 = Var1;
Var2.TestName = "aaa";
}
}
When I debug the value of Var1.TestName
I get "aaa"
but originally it was "Me"
. How can I separate each var but still Var2
gets its initial values from Var1
?
C# is a pass by reference language, when dealing with objects. So when you say
Var2 = Var
, you're saying thatVar2
now holds the address of whatever addressVar1
was holding, effectively making them point to the same object.One work around is to turn it into a pass by value, like so:
Or, if you will be using more values and this is an overly simplified example, you can use another approach:
And in your test class:
Here is your problem:
Var2 = Var1;
is actually a reference copy! This means that theVar2
will take the address ofVar1
and no matter what you modify in either of them, it will be visible in the other. To get that, I would recommend using a copy ofVar2
. To do so, create a method in yourtestClass
class.Now you can assign the value like this:
Var2 = Var1.copy();