- Home /
Copy static Dictionary value for local change
Hello I tried create list of monster using static dictionary and I want the value of that dictionary to change in only in local, here's some example
public class A {
public string name;
public A (string name) {
this.name = name;
}
}
public class m {
public static Dictionary<string, A> dict = new Dictionary<string, A>();
}
public class mon : MonoBehaviour {
private A tes;
// Use this for initialization
void Start () {
m.dict.Add("a", new A("its A!"));
tes = m.dict["a"];
tes.name = "B";
Debug.Log(tes.name);
Debug.Log(m.dict["a"].name); // why this return B instead of "its A!"
}
}
I don't understand why static dictionary value get changed is there something I miss?
I tried to figure it for hours and still can't get it, and I can't get any match keyword for my problem
When you assign a reference type you just assign a pointer on the original object and not a new copy . Which means in this occasion that when you say tes = m.dict["a"] the value of the m.dict["a"] is pointing to tes and it is not a copy of tes. So you have 2 references of the same Object, changes applied to it either with tes.name = "B" or dict["a"].name = "B" will have exacty the same result. Read the C# documentation on referencetypes and value types. Cheers.
PS. nothing to do with static accessor.
Thank you! this really make me crazy, I don't know about reference I need initialize first tes = new A(m.dict["a"].name) And just found out about deep cloning object Oh god I need to learn more, again thank you!
Your answer
![](https://koobas.hobune.stream/wayback/20220612144657im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
typedefing in unity 1 Answer
Need help with targetting 1 Answer
adding dictionary in the game 0 Answers