[Solved] Assigning variable without changing the value of assigned variable when the variable value is changed?

Hello, I have a problem with variable declaration. I already google it but doesn’t really know what the keyword would be and don’t find the answer, so I try to ask in this place instead. Sorry if the title is hard to understand…

So, I have this script:

 public static CharacterDurability CountBoundary(CharacterDurability durability,PlayerHealth health)
        CharacterDurability temp = durability;
        CharacterDurability temp2 = durability;
        CharacterDurability temp3 = temp2;

        Debug.Log("durability1 =" + durability.stamina);

        temp.stamina = durability.stamina + (durability.stamina * (health.Mood / 100)) * 20 / 100;

        Debug.Log("durability2 =" + durability.stamina); 
        Debug.Log("temp2 =" + temp2.stamina);
        Debug.Log("temp3 =" + temp3.stamina);
        // durability changed after using formula above. I dunno how to make things work. Help!!
        return temp;

The output is
durability1 = 80
durability2 = 92
temp2 = 92
temp3 = 92

And then I changed the formula to

temp.stamina = temp.stamina + (temp.stamina * (health.Mood / 100)) * 20 / 100;

But the value still same as before

I don’t want the values of durability to be changed (still 80), but I want to use variable temp with value of durability assigned. How can I do that? Please help me…

I’m using 5.4.0f3 personal edition, with visual studio
And using Wingdows 10 64 bit as OS…


OK, I found the answer. What I need is change the temp declaration to this one

CharacterDurability temp = (CharacterDurability) durability.MemberwiseClone() ;

And it all work now.

If I am understanding this correctly, I think that you can fix your problem by changing

CharacterDurability temp = durability;


CharacterDurability temp = new CharacterDurability();

As your code is right now, your three temp variables all reference the original durability instance of “CharacterDurability” that is passed into the method. Because of this, a change to one of the temp variables is a change to all of them. You need to create a new instance of CharacterDurability so that you can alter its variables (stamina in this case), without altering the stamina variable of the original.