Having variables change values on each other’s changes

Good evening,

I’ve had an idea before going to bed which I quite can’t wrap my head around on how to do it.

imagine I had a spawn-system that I can tell to spawn either rocks or trees and I have two values that represent the chance to spawn either one of these. I could easily just for myself always have the sum of the values equal 100%.

And here comes the question, would it be possible to implement a ceiling for these two values to meet and have them change depending on their sum?

for example, both values sum has to be 100. Changing value A to 70 automatically sets value B to 30.

I hope I’m not too confusing here and sorry for any grammar mistakes. Would love to hear some other devs thoughts on this!

With two numbers it’s easy to just special-case it: when you set one number, always update the other number to be 100 minus the first number.

With many numbers a more generalized approach is needed. A few years back I made such a demo and I enclose the full project package here for your amusement.

NOTE: there are MANY possible ways to make this work. This is only one chosen way.

5922950–632948–MutuallyLimitedSliders.unitypackage (11.1 KB)

Thank you for your answer! I see though that your demo is doing this is in playmode. Is there anyway to do this in the editor when not playing?

Might even be easier: look into the OnValidate() method.

You implement that method and you can just do the adjustment right there.

Could this be done through Get/Set methods? Using Properties - C# | Microsoft Learn

1 Like