- Home /
constructor called multiple times
Why is the constructor of Custom called 4 times when you start "Play Mode"?
public class TestMe : MonoBehaviour
{
public Custom d ;
}
[Serializable]
public class Custom
{
static int timesCalled = 0;
public Custom()
{
timesCalled++;
if (timesCalled>1) Debug.LogError("Called Multiple Times: "+ timesCalled);
}
}
Bug Report: https://fogbugz.unity3d.com/default.asp?847340_u67k8s7e0hhcdhdf
Answer by Bunny83 · Nov 02, 2016 at 09:28 PM
Because the constructor has no meaning for objects that are serialized by Unity. Unity recreates the object each time the object is deserialized. Custom serializable classes are just data classes. If you want a post-deserialization callback you might want to implement the ISerializationCallbackReceiver interface.
Apart from that you should keep in mind that when you have your TestMe class attached to several objects your static counter will go up multiple times. Further more keep in mind that prefabs are object instances as well.
Your answer
Follow this Question
Related Questions
C# Constructor in MonoBehaviour 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Illuminating a 3D object's edges OnMouseOver (script in c#)? 1 Answer