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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

The number didn't add in update

Discussion in 'Scripting' started by Enaldy, Apr 27, 2022.

  1. Enaldy

    Enaldy

    Joined:
    Jun 28, 2019
    Posts:
    6
    I have a script that add number if the score mod 100 equals to 0, but the number didn't add
    Code (CSharp):
    1. if (!gameOver && gameStarted && !hit.stop)
    2.         {
    3.             transform.Translate(-Vector3.right * Time.deltaTime * (movingSpeed + num), Space.World);
    4.             score += Time.deltaTime * movingSpeed;
    5.             if (score % 100 == 0) num += (movingSpeed * 0.1f);
    6.         }
     
  2. Enaldy

    Enaldy

    Joined:
    Jun 28, 2019
    Posts:
    6
    nah, I get it, the variable is float while the equation is integer
     
  3. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,735
    It's exceedingly unlikely for
    score % 100 == 0
    to ever be true since
    score
    seems to be a float. It will have values like: 99.56, 99.89, 100.12, etc... Never hitting exactly 100. Pretty sure what you want is something like this:

    Code (CSharp):
    1. public float speedIncrement = 0.1f;
    2. public float initialMoveSpeed = 5; // set this to whatever you want
    3.  
    4. float movingSpeed;
    5.  
    6. void Start() {
    7.     movingSpeed = initialMoveSpeed;
    8. }
    9.  
    10. void Update() {
    11.     if (!gameOver && gameStarted && !hit.stop)
    12.     {
    13.         // accumulate score
    14.         score += Time.deltaTime * movingSpeed;
    15.  
    16.         // move
    17.         transform.Translate(-Vector3.right * Time.deltaTime * movingSpeed, Space.World);
    18.  
    19.         // update movement speed if necessary
    20.         float hundreds = Mathf.Floor(score / 100f);
    21.         movingSpeed = initialMoveSpeed + (hundreds * speedIncrement);
    22.     }
    23. }
     
    Last edited: Apr 27, 2022
  4. Enaldy

    Enaldy

    Joined:
    Jun 28, 2019
    Posts:
    6
    thanks! that works well here