Why does { get set } not work?

So I have this script here:

    [SerializeField] float diameterKm = 0f; // Diameter in km
    public float DiameterKm {
        get { return diameterKm; }
        set { diameterKm = value; Radius = (double)diameterKm * 500.0; } // Updates radius
    }

    [SerializeField] double radius = 0.0; // Radius in meters
    public double Radius {
        get { return radius; }
        set { radius = value;  }
    }

So what should happen ( Or at least I hoped it would) is that when I change the “diameterKm” in the inspector, it would also recalculate the radius, but it dosen’t and I have no idea why, my best guess is that there us something small that I overlooked.

The inspector sets* the value of the variable directly. It does not call the Property you defined. Look into OnValidate for inspector stuff.

4 Likes

As said before me, properties are not set by Unity. But you can still use your validation code with this little trick:

void OnValidate()
{
    DiameterKm = diameterKm;
}

This means, that Unity will set the backing field directly, but then call OnValidate for you. There you can take the inspector value and set it through your property again, applying your validation.

1 Like