Sign in to follow this  

Unity Data linking varibles

This topic is 670 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi,

 

I have X amount of variables, they all need to add up to an amount (100). There are some conditions that must be met.

 

  • When I set one variable, the others need to reduce/increase.
  • the variables can not go less than 0.  
  • The variables must stay at the same ratio, unless one or more is decreased to 0

Currently I have an issue where I will have a set of varibles: 1, 50, 25,24 . And I want to increase the first variable to 91.

 for (int i = 0; i < arraySize; i++)
        {
            int SliderValue = aarray[i]
            if (SliderValue!= oldValue) //only update when changed
            {
                int difference = SliderValue - oldValue;//how much did the slider change by
                oldValue = SliderValue; //update the old value

                int amount = difference / arraySize - 1);
                int remainder = 0;
                if (difference % arraySize - 1) != 0)//We need to know if it has rounded down
                {
                    remainder = difference % (arraySize -1);

                }

                for (int j = 0; j < arraySize; j++) //Change the other values
                {
                    if (j == i)//dont change youself
                        continue;

                    int b = array[j];
                    if (remainder != 0 && (b>= 0 && b <= goal))
                    {
                        if (remainder < 0)
                        {
                            increaselowest(array, /*element to ignore*/i, Mathf.Abs(remainder));

                        }
                        else
                            decreaselargest(array, /*element to ignore*/i, Mathf.Abs(remainder));

                        remainder = 0;

                    }

                    b= b- amount;
                   Oldvalue= b.intValue;
                }
               
            }

 apologies if there are bugs/errors in this code. It was written using Unity serialization stuff, and had to edit it down.

 

increaselowest will find the lowest variable in the array and increase it by the amount.

DecreaseLargest will find the largest value and decrease it by an amount.

 

 

My problem comes when I increase by a large amount. with the numbers 1, 50, 25,24. and increase the first variable by 90, it means the other numbers need to decrease by 30 (3*30 = 90). However this will result in the last two variables being negative. 

 

I could reduce the other variable when a var goes negative, but I don't know how many varibles are in the list.

 

I cant sum the negative numbers and reduce the positive numbers by that absolute value, as that inturn may make the a number negative again.

 

I feel like the solution will be some recursion, but I cant think of a nice clean way to do it.

 

Any thoughts?

Share this post


Link to post
Share on other sites

Now that we have some real values perhaps we can discuss from chat. Note according to me pulling down 30 by each three-last variable implies you're breaking the ratio between them but I guess that's lost in translation.

a= 1, b=50, c=25, d=24 sum_abcd=100
a=91, b=50, c=25, d=24 sum_abcd=190; sub_bcd=99

a must stay 91. 100 - a = 9 (I guess that's what Madolite tried to tell you). Divide bcd by 100 and now you got a nice 3D vector if you're familiar with this. Normalize it. It'll be

b=.505050, c=.252525, d=.242424 sum_bcd=~100

This is your new 100%. Multiply those values by 9.

b=4.545454~5, c=2.272725~2, d=...~2

What a coincidence, they add up to 9.

 

I still haven't understood the deal with negatives. You write they cannot go lower than zero... but can start less than zero?

Try counting from the minimum.

Edited by MaxDZ8

Share this post


Link to post
Share on other sites
For the list, L=(1, 50, 25, 24), and a selected index, idx=0:

1. Find the sum of the others: sum = 50 + 25 + 24 = 99. You may want to cache these ratios until idx changes.
2. After changing L[idx], find remaining amount: remaining = 100-L[idx]
3. Adjust other values according to their proportion, with rounding: (L[jdx]*remaining)/sum.
4. Add or remove 1 to one of the other sliders to correctly account for rounding corner cases, if the sum doesn’t match 100.


EDIT:
Here’s a quick test in powershell:
foreach ( $z in ((50,25,24), (25,25,25)) ) {
  foreach ( $y in (0,1,50,99,100) ) {
    $remaining = 100-$y;
    $total = $z | measure -sum | select -expand sum;
    $others = $z |% {
      [Math]::floor(($_*$remaining + $total/2)/$total);
    };
    $all = ,$y + $others;
    $sum = $all | measure -sum | select -expand sum;

    $adj = 100-$sum;
    $all[1] += $adj;
    $sum += $adj;

    "sliders=$all sum=$sum"
  }
}
[tt]
sliders= ? 0 ? 51 ? 25 ? 24 sum=100
sliders= ? 1 ? 50 ? 25 ? 24 sum=100
sliders= 50 ? 25 ? 13 ? 12 sum=100
sliders= 99 ? ? 1 ? ? 0 ? ? 0 sum=100
sliders=100 ? ? 0 ? ? 0 ? ? 0 sum=100

sliders= ? 0 ? 34 ? 33 ? 33 sum=100
sliders= ? 1 ? 33 ? 33 ? 33 sum=100
sliders= 50 ? 16 ? 17 ? 17 sum=100
sliders= 99 ? ? 1 ? ? 0 ? ? 0 sum=100
sliders=100 ? ? 0 ? ? 0 ? ? 0 sum=100
[/tt] Edited by fastcall22

Share this post


Link to post
Share on other sites


Add or remove 1 to one of the other sliders to correctly account for rounding corner cases, if the sum doesn’t match 100.

 

This part could get a bit arbitrary. If you had {25,25,25,25} and increased one of them by 1, where do you take the 1 from?

 

I mean you could pick an arbitrary (even random) solution, but I'm wondering about the use case here. Could you just use floats?

Share this post


Link to post
Share on other sites

This topic is 670 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Forum Statistics

    • Total Topics
      628738
    • Total Posts
      2984464
  • Similar Content

    • By INTwindwolf
      THE PROJECT

      INT is a 3D Sci-fi RPG with a strong emphasis on story, role playing, and innovative RPG features such as randomized companions. The focus is on the journey through a war-torn world with fast-paced combat against hordes of enemies. The player must accomplish quests like a traditional RPG, complete objectives, and meet lively crew members who will aid in the player's survival. Throughout the game you can side and complete missions through criminal cartels, and the two major combatants, the UCE and ACP, of the Interstellar Civil War.
      Please note that all of our current positions are remote work. You will not be required to travel.
      Talent Needed
       
      Unity Engine Programmer
      Website Administrator
      3D Animator
      We have made great strides in the year 2017! INT has received a comprehensive face-lift compared to the start of the year. We look forward to a productive, fruitful year 2018!
      Revenue-Share
      This is the perfect opportunity to get into the game development industry. Being an Indie team we do not have the creative restrictions often imposed by publishers or other third parties. We are extremely conscientious of our work and continuously uphold a high level of quality throughout our project.
      We are unable to offer wages or per-item payments at this time. However revenue-sharing from crowd-funding is offered to team members who contribute 15-20 hours per week to company projects, as well as maintain constant communication and adhere to deadlines. Currently the crowd-funding campaign is scheduled for the year 2018. Your understanding is dearly appreciated.
       
      Thank you for your time! We look forward to hearing from you!
       
      John Shen
      HR Lead
      Starboard Games LLC
    • By Apollo Cabrera
      Energy particles being harnessed by collection multi-hedron energy matrix. Whuuuttt?
      Love it :)
    • By AndySv
        Total Music Collection (http://u3d.as/Pxo)   THE COLLECTION CONTAINS:   Mega Game Music Collection   Universal Music Collection   Huge library of high quality music for any project! All at an incredibly low price!   - 2,5GB of high quality audio - 100+ different music tracks - Loop and short versions   Action, fantasy, casual, horror, puzzle, epic, dramatic, romantic, positive, inspiring, motivational and more!
    • By Dafu
      FES Retro Game Framework is now available on the Unity Asset Store for your kind consideration!
      FES was born when I set out to start a retro pixel game project. I was looking around for an engine to try next. I tried a number of things, from GameMaker, to Fantasy Consoles, to MonoGame and Godot and then ended up back at Unity. Unity is just unbeatable in it's cross-platform support, and ease of deployment, but it sure as heck gets in the way of proper retro pixel games!
      So I poured over the Unity pipeline and found the lowest levels I could tie into and bring up a new retro game engine inside of Unity, but with a completely different source-code-only, classic game-loop retro blitting and bleeping API. Months of polishing and tweaking later I ended up with FES.
      Some FES features:
      Pixel perfect rendering RGB and Indexed color mode, with palette swapping support Primitive shape rendering, lines, rectangles, ellipses, pixels Multi-layered tilemaps with TMX file support Offscreen rendering Text rendering, with text alignment, overflow settings, and custom pixel font support Clipping Sound and Music APIs Simplified Input handling Wide pixel support (think Atari 2600) Post processing and transition effects, such as scanlines, screen wipes, screen shake, fade, pixelate and more Deploy to all Unity supported platforms I've put in lots of hours into a very detail documentation, you can flip through it here to get an better glimpse at the features and general overview: http://www.pixeltrollgames.com/fes/docs/index.html
      FES is carefully designed and well optimized (see live stress test demo below). Internally it uses batching, it chunks tilemaps, is careful about memory allocations, and tries to be smart about any heavy operations.
      Please have a quick look at the screenshots and live demos below and let me know what you think! I'd love to hear some opinions, feedback and questions!
      I hope I've tickled your retro feels!



      More images at: https://imgur.com/a/LFMAc
      Live demo feature reel: https://simmer.io/@Dafu/fes
      Live blitting stress test: https://simmer.io/@Dafu/fes-drawstress
      Unity Asset Store: https://www.assetstore.unity3d.com/#!/content/102064

      View full story
    • By Dafu
      FES Retro Game Framework is now available on the Unity Asset Store for your kind consideration!
      FES was born when I set out to start a retro pixel game project. I was looking around for an engine to try next. I tried a number of things, from GameMaker, to Fantasy Consoles, to MonoGame and Godot and then ended up back at Unity. Unity is just unbeatable in it's cross-platform support, and ease of deployment, but it sure as heck gets in the way of proper retro pixel games!
      So I poured over the Unity pipeline and found the lowest levels I could tie into and bring up a new retro game engine inside of Unity, but with a completely different source-code-only, classic game-loop retro blitting and bleeping API. Months of polishing and tweaking later I ended up with FES.
      Some FES features:
      Pixel perfect rendering RGB and Indexed color mode, with palette swapping support Primitive shape rendering, lines, rectangles, ellipses, pixels Multi-layered tilemaps with TMX file support Offscreen rendering Text rendering, with text alignment, overflow settings, and custom pixel font support Clipping Sound and Music APIs Simplified Input handling Wide pixel support (think Atari 2600) Post processing and transition effects, such as scanlines, screen wipes, screen shake, fade, pixelate and more Deploy to all Unity supported platforms I've put in lots of hours into a very detail documentation, you can flip through it here to get an better glimpse at the features and general overview: http://www.pixeltrollgames.com/fes/docs/index.html
      FES is carefully designed and well optimized (see live stress test demo below). Internally it uses batching, it chunks tilemaps, is careful about memory allocations, and tries to be smart about any heavy operations.
      Please have a quick look at the screenshots and live demos below and let me know what you think! I'd love to hear some opinions, feedback and questions!
      I hope I've tickled your retro feels!



      More images at: https://imgur.com/a/LFMAc
      Live demo feature reel: https://simmer.io/@Dafu/fes
      Live blitting stress test: https://simmer.io/@Dafu/fes-drawstress
      Unity Asset Store: https://www.assetstore.unity3d.com/#!/content/102064
  • Popular Now