I have a number that I want to be editable in the inspector. However, I want to restrict that number to be a multiple of 10. I can always just go into the code and set it to the nearest multiple of 10, but I'd rather force it in the inspector. I am willing to use an int, float, Vector, or really any sort that can hold a number. How can I do this?
Answer
I'd use OnValidate
for this. It gets called anytime the user changes something in the Inspector, but only in the Unity editor, so it doesn't add unnecessary checks into a compiled build of the game.
public class SnapTest : MonoBehaviour {
[Range(min:-50, max:50)]
public float snappedValue;
void OnValidate()
{
snappedValue = Mathf.Round(snappedValue / 10f) * 10f;
}
}
This gives you a snapping slider like this:
No comments:
Post a Comment