Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Forcing Public Integer Variable to be divisible by something.

Discussion in 'Scripting' started by hikariakio, Sep 15, 2019.

  1. hikariakio

    hikariakio

    Joined:
    Dec 19, 2016
    Posts:
    25
    Hello guys, I need a public integer variable that is Between 1 and 90 and whenever someone changes the variable in the inspector , I want it to change automatically to the nearest integer divisible by 9.

    Code (CSharp):
    1. [Range(1,90)]
    2. public int rollingSpeed = 5;
    How about setting positive integer variables that are forced to be set 0 or 1 or may be something if they are changed into negative numbers in the inspector.
     
    Last edited: Sep 15, 2019
  2. Adrian

    Adrian

    Joined:
    Apr 5, 2008
    Posts:
    1,051
    Depending on what you want to do, I'd just change the range to 0-10 and then multiply rollingSpeed by 9 in your code. This way the value is always valid and you save yourself the validation.

    Otherwise, you can use the OnValidate message in your MonoBehaviour scripts. This method will be called when the script is edited in the inspector and allows you to round the value to nearest multiple of 9.

    In my experience, OnValidate hasn't always been very reliable. You'd want to also implement the check in OnEnable to make sure it's always properly applied.
     
    Joe-Censored likes this.
  3. hikariakio

    hikariakio

    Joined:
    Dec 19, 2016
    Posts:
    25
    Thanks..I am soo stupid.. T_T I just realized that I can change those values easily in Start or Awake.......

    Thanks for your answer