I noticed a very strange behavior when trying to do the following:
Have two instances of a class, and in Start(), assign one of the instances to the other. This links both instances, so if a value in one of the instance’s variables is changed, the one in the other instance is, too. So far, so good.
However, if a value is changed in the inspector (for example, typing in a string or int in an inspector field), for some reason, only the second instance accepts any changes! Am I missing something here?
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Test : MonoBehaviour {
public MyClass myClass1 = new MyClass();
public MyClass myClass2 = new MyClass();
[System.Serializable]
public class MyClass {
public int count;
}
void Start() {
myClass2 = myClass1;
}
}
This actually isn’t related to value vs Reference types but to how Unity’s serialization system works.
First of all when you create a serialized variable in a MonoBehaviour (has a serializable type and is public or marked with SerializeField), you don’t need to create an instance since the Inspector does this for you.
Next thing is when the variable is serialized Unity doesn’t serialize your custom class on it’s own. It just serializes it’s content along with the MonoBehaviour. So if you have two serialized variables referencing the same instance, once serialized and deserialized you have two seperate instances.
Unity also doesn’t support inheritance for serializable custom classes since Unity serializes the data based on the variable’s type, not the actual type.
The question is now what you actually want to achieve. If you want to reference an object from Multiple scripts / variables and they should all reference the same instance, you have to use either a class derived from MonoBehaviour or ScriptableObject.