2D game Score based on Time

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

Google is your friend! In this case “second timer in unity” and typically the code would go in the Update() event

1 Like

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).

public Text ScoreTextComponent;  //Assign this in the inspector
private int score = 0;  //current score as an integer
private float secondTimer = 0f;    //timer for counting to 1 second

void Update()
{
    secondTimer = secondTimer + Time.deltaTime;
    if (secondTimer >= 1f)
    {
        addScore();
        secondTimer = secondTimer - 1f;
    }
}

private void addScore()
{
    score++;
    ScoreTextComponent.text = score.ToString();
}

Thank you so much ! that worked fine and was easy to understand! Appreciatet !

1 Like