- Home /
Serialized Parameter Constructor?
I have a custom (non monobehaviour) value type called "Trait" that I want to initialize from the Unity Inspector, but it seems that only the default constructor can get called from the inspector, and I want to keep the internal state of this type unexposed and immutable. ie, the type looks like this:
[Serializable]
public readonly struct Trait : IComparable, IComparable<Trait>, IEquatable<Trait>, IConvertible, IFormattable
{
private readonly float MaxVal, MinVal, Value;
public Trait(float value, float max, float min)
{
if (max < min) throw new ArgumentException("Max val cannot be less than min val.");
MaxVal = max;
MinVal = min;
if (value > max) Value = max;
else if (value < min) Value = min;
else Value = value;
}
// Operations, conversions, etc ...
}
The point is that the representation guarantees that the current value can never go beyond the supplied max and min values.
In any case, the way I have it implemented, I cant initialize the value from the inpsector. I can think of a couple possible solutions, but none of them seem ideal:
Remove the readonly modifier and add private serialized properties that are used in the default constructor. This wouldn't horribly undermine the representation, but it would cause me to lose whatever performance is gained from having the struct be readonly. Also the compiler complains because it cant guarantee that those values have been assigned to...
Create a custom inspector/editor for this type that creates three properties and then uses them to call the parameterized constructor. I'm not sure this is possible? serializedObject is read only from the Editor class, so it doesnt seem like theyd want you to reinstantiate it. Plus it is a unity Object, which wont work with this non-monobehaviour.
Any suggestions / ideas?
Answer by Damnsatinist · Nov 16, 2019 at 07:16 AM
Well, I didn't solve it the way I would've liked but it does work:
public struct Trait : ... ... ...
{
public float MaxVal { get => maxVal; }
public float MinVal { get => MinVal; }
[SerializeField] private float maxVal, minVal, value;
// etc
}