Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

brain aneurysm over this math, max value int, current value, fill max 1.000?

Discussion in 'Scripting' started by Unlimited_Energy, Aug 13, 2019.

  1. Unlimited_Energy

    Unlimited_Energy

    Joined:
    Jul 10, 2014
    Posts:
    469
    me and math don't mix well. I cannot figure out this simple equation. I have different achievement int values a player needs to reach. Some are 1,000, some are 100 and some are 350,000. how can I take the achievement amount, say 350,000 a player needs to reach, the current value(lets say its 18,000) and fill the progress bar which is a float 1 being max(1.000) out of the current and max values of the achievement to the current percentage of the achevement completed(in this case 18,000 of 350,000)?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    The ratio you want would be 18000 divided by 350000.

    However, if you are storing those values in integers, the code will divide integers which will give you zero. This might be where you are having difficulty.

    What this means you may have to cast the number to a float before dividing it.

    Let's say these are your numbers

    Code (csharp):
    1. int achieved = 18000;
    2. int needed = 350000;
    If you divide those, you will get zero every time, due to integers rounding down.

    Code (csharp):
    1. float fraction = achieved / needed; // fraction will always be zero for above values
    So you cast at least one of the integers to a float before dividing it:

    Code (csharp):
    1. float fraction = (float)achieved / needed;
    That causes the divide to be a floating point divide instead of an integer divide, and you should get 0.0514...

    Now you can just assign fraction to the progress bar graphic, which would be your typical Image set to "Filled" type.
     
  3. Unlimited_Energy

    Unlimited_Energy

    Joined:
    Jul 10, 2014
    Posts:
    469