OnSerialize event

Is possible to be told after serialization occurs for objects, in the Editor?


I know that Unity3D serializes some variables (as described in the SerializeField manual page).

After importing a script something in my project, clicking play, or going back from play mode, Unity3D recreates all the objects in memory, and reset all serializable fields. That’s why when I Debug.Log() a public variable (like int), it says the default value, but when I access it with other script it says the previous stored (serialized) value.

What I want to know is when serialization takes place, to sew my variables in the editor to a more proper object. The manual refers to this process of sewing:

Hint: Unity won’t serialize Dictionary, however you could store a List<> for keys and a List<> for values, and sew them up in a non serialized dictionary on Awake(). This doesn’t solve the problem of when you want to modify the dictionary and have it “saved” back, but it is a handy trick in a lot of other cases.

Thing is, in the Editor I can’t use the Awake function. I’ve tried OnEnable, OnBecameVisible, Start, Awake and Reset with no help: none of these functions are called after I make a change in the scripts. The constructor is called, but as I mentioned earlier, it contains the constructor values.

Any help would be much appreciated.

You might be able to use a twist on lazy initialization:

//by default, we have a 'null' dictionary
//the first time we access it, create and sew
private Dictionary<Foo> _d;
public Dictionary<foo> d
{
	get
	{
		if (_d == null)
		{
			_d = new Dictionary<foo>();
			Sew();
		}
		return _d;
	}
	set
	{
		_d = value;
	}
}

public void Sew()
{
	//do stuff
}

This seems like it should re-create and re-sew the dictionary each time you get a new object.

This blog post answered my question: