Calculating and displaying % - why doesn't this work?

Hi again,

Back with what should be an easy problem, but is driving me nuts.

Trying to calculate and display percentage of pick ups collected in the Roll a Ball tutorial, but my percentages go from 0% to 100% with nothing in between.

void SetCountText () // sets count, score and you win text.
    {
        countText.text = "Count: " + count.ToString();
        scoreText.text = "Score: " + score.ToString();
        if (count >= 1)
        {
            //winText.text = "Level Complete!";
            percent = (count / 12) * 100;
            percentText.text = percent.ToString() + "% of Pick Ups Collected.";
           
        }
    }

I have a float named percent declared earlier in the program. 12 pick ups. Should just be able to divide count (pick ups collected so far) by total pick ups (12) * 100 to get percent.

Can’t seem to figure out what I am doing wrong.

Again, thanks in advance.

The code you have there looks right to me. Does it go from 0 to 100% as soon as you collect one item?

No, the display stays at 0% until I pick up the 12th item them it jumps straight to 100%

Okay, so the next thing to check is if it’s being called when you collect the other pickups - it probably is, but try adding a Debug.Log statement to the start of the method. If that is called every time you collect another object, add more log messages to the method.

The problem is that “count” is an integer, and so is “12”. So when you write “count / 12”, the C# compiler takes this as integer division.

Easiest way to fix it is to instead write count / 12f, making the 12 a floating-point literal. C# will then do floating-point division.

5 Likes

Once again Joe comes to the rescue.

Change 12 to a float worked.
I changed the total to 146 to match all the pickups in the level and added (“#.00”) to my display string and it all works great now.

void SetCountText () // sets count, score and you win text.
    {
        countText.text = "Count: " + count.ToString();
        scoreText.text = "Score: " + score.ToString();
        if (count >= 1)
        {
            //winText.text = "Level Complete!";
            percent = (count / 146f) * 100;
            //percent = (int)percent;
            percentText.text = percent.ToString("#.00") + "% of Pick Ups Collected.";
           
        }
       
    }

Thanks again to Joe and Philip.

I’m still working on the Move.Towards Joe recommended. I couldn’t get it to work, but looking at it again, I think I may know why now. If not I’ll be back with another question. Almost ready to present my version of the tutorial for critique.

2 Likes

Had the same problem, was trying to get percentages using Integer math, changed vars to float and it worked. I had even tried casing the calc to float and that didn’t work;

Debug.Log would have caught this right away.
https://www.youtube.com/watch?v=A-Q5BsnnXZ8