I have some data types' properties that depend on the input given into other attributes, but I haven't found in the Unity's API an elegant way to update them automagically on the Inspector.
As an example, let's say I have a struct that has a divider value. Since I want to save division computations, I also have on the class a multiplicative inverse value that depends on the divider's, so I'd rather multiply instead of dividing.
Example Code Snippet:
[Serializable]
public struct SomeNumbers
{
[SerializeField] private float divider;
private float multiplicativeInverse;
/// When the divider is set, the multiplicative inverse is also set.
public float Divider
{
get { return divider; }
set
{
divider = value;
multiplicativeInverse = (1f / divider);
}
}
public float MultiplicativeInverse
{
get { return multiplicativeInverse; }
private set { multiplicativeInverse = value; }
}
/// Constructor.
public SomeNumbers(float divider) : this()
{
Divider = divider;
}
}
public class ExampleScript : MonoBehaviour
{
public float value;
public SomeNumbers numbers;
void Update()
{
float result = (value * numbers.MultiplicativeInverse); /// Instead of (value / numbers.divider)...
Debug.Log("Result: " + result.ToString());
}
}
What I'd like, is that each time I change the divider's field, the value under the hood (this case the multiplicative inverse) also gets changed, as if I used the Divider's setter. Since the idea is to have an independent data type, the approach of using OnValidate on a class that contains this struct would not be applicable, since that would be a hard case.
I could also set the Divider's setter on each class at Start/Awake do that for me, but that would be prone to be forgotten. I know about Property Drawers , but I am not sure if that would be the right approach.
I hope the question was clear enough, if not make me know so I correct it. Thanks in advance.