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

How to link two values to change second value proportionally to the first one.

Discussion in 'Scripting' started by nbg_yalta, Aug 4, 2014.

  1. nbg_yalta

    nbg_yalta

    Joined:
    Oct 3, 2012
    Posts:
    378
    For example I have

    value1 = 6;
    value2 = 3;

    When the value1 decreasing I need to value2 decrease proportionally. Value1 goes to 3, value2 goes to 1.5 etc.
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,738
    Depends on how you use value2 and which language you're in. If you're just using value2 in script, for example, you could make it a property, in C#:
    Code (csharp):
    1. public float value1 = 6f;
    2. public float value2 {
    3. get {
    4. return value1 * 0.5f;
    5. }
    6. set {
    7. value1 = value * 2f; //"value" is a special variable that is always existent in a "set" function
    8. }
    9. }
    (don't know the JS syntax for properties offhand)

    Properties, unfortunately, don't show up in the inspector.

    If you just need to change values themselves, you can use OnValidate, which is called when any public member is changed... though you can't automatically tell which one has changed, so this might be inadequate.
     
  3. nbg_yalta

    nbg_yalta

    Joined:
    Oct 3, 2012
    Posts:
    378
    Thanks for reply, but I dont really think this is a right way for doing what is needed, considering that the values can be completely different, for example 5.5 and 1, or 7 and 2 etc.
     
    powerpointranger likes this.