Search Unity

2D game Score based on Time

Discussion in 'Getting Started' started by Dervl3nn4n, Jan 14, 2020.

  1. Dervl3nn4n

    Dervl3nn4n

    Joined:
    Dec 19, 2015
    Posts:
    4
    Hello everybody,
    I have a small problem, because im pretty new to unity.
    I have this 2d game where i play as a ball that can roll to the left and right.
    Now i want to add a Score that goes up every second.
    I already have a Ui canvas and text so on the play screen it says "0"
    where do i need to make a script and what goes into the script so my timer works?
    thankful for every bit of help.

    kind regards
     
  2. JeffDUnity3D

    JeffDUnity3D

    Joined:
    May 2, 2017
    Posts:
    14,446
    Google is your friend! In this case "second timer in unity" and typically the code would go in the Update() event
     
    Joe-Censored likes this.
  3. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Update or a coroutine. Update is easier to understand for someone new to Unity, but coroutine might be the better tool. Example using Update below (untested because I just wrote it directly into the forum, so sorry if I made a typo).

    Code (csharp):
    1. public Text ScoreTextComponent;  //Assign this in the inspector
    2. private int score = 0;  //current score as an integer
    3. private float secondTimer = 0f;    //timer for counting to 1 second
    4.  
    5. void Update()
    6. {
    7.     secondTimer = secondTimer + Time.deltaTime;
    8.     if (secondTimer >= 1f)
    9.     {
    10.         addScore();
    11.         secondTimer = secondTimer - 1f;
    12.     }
    13. }
    14.  
    15. private void addScore()
    16. {
    17.     score++;
    18.     ScoreTextComponent.text = score.ToString();
    19. }
     
  4. Dervl3nn4n

    Dervl3nn4n

    Joined:
    Dec 19, 2015
    Posts:
    4
    Thank you so much ! that worked fine and was easy to understand! Appreciatet !
     
    Joe-Censored likes this.