Monday, March 19, 2018

unity - How can I have a value increase by multiples of 10 in the inspector?


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:


Example of the Inspector UI


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...