- Home /
Can I set default values for a nested class?
I have a class that applies different visual effects depending on the time of day. The different times of day are represented as a nested class, like so:
public class TimeOfDayFadeInObjects : MonoBehaviour
{
[System.Serializable]
public class FadeObject
{
public string name;
public float maxOpacity = 1f;
//whole bunch more stuff
}
public List<FadeObject> objectsToFade;
//whole bunch more stuff
}
When I create a new instance of FadeObject in the Inspector, maxOpacity has it's value set to 0. Is there any way to make it default to 1?
I have tried setting up a custom constructor for FadeObject, like so:
public FadeObject()
{
maxOpacity = 1f;
}
but this only seems to have the effect of bolding the values it touched in the inspector, not setting the default (I assume that Unity goes along and sets them all to a default after the constructor has run, but notices the divergence)
Answer by v21 · Jul 23, 2014 at 01:27 PM
So, half a year later: The answer is no.
The best workaround I have found is to use Reset() to :
create the List
create an instance of FadeObject
then add it as the first element
and then any subsequent elements will use the "copy last element" logic built into Unity to be somewhere close to default values
Answer by chechoggomez · Apr 08, 2015 at 02:17 AM
The inspector overwrites values of serialized items after construction. For the behavior the you want, you can set values on the constructed Data instances in Start or OnAfterDeserialize.
Take a look here:
http://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.html http://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.OnAfterDeserialize.html http://docs.unity3d.com/ScriptReference/ISerializationCallbackReceiver.OnBeforeSerialize.html
Your answer
Follow this Question
Related Questions
Why does collapsing sprite renderer make objects not draggable in scene view? 2 Answers
Learning inheritance, need clarification 1 Answer
Displaying public variables in the inspector 2 Answers
[SerializeField] makes fields visible and editable in the inspector 1 Answer
Query whether inspector is folded? 1 Answer