Associate time and distance for a score system

Hello, I introduce myself, my name is Samih.

I just start game development in unity.

I am currently developing a simple 2D game to learn many things about game development.

Nevertheless, I have some issues to create a score system.

Indeed, in the game, the score of the character is a function of the distance travelled (the scene and the character are static, only the textures move = treadmill effect).

So, I wanted to link the time spent by the player (before the game over) with distance.

when time increases, it hads values to the distance travelled.

(for example: for each seconds, it adds 5 points to distance travelled.)

I don’t know how to do it

How can I do this?

Thank you.

I’d be tempted to look into using Time.deltaTime to assess the time passed. I’d create a float to hold the value of your score and each Update add Time.deltaTime to the score variable.

The value can be multiplied by a score multiplier if desired. Something like:

Public Class ClassName : MonoBehaviour {
    float score = 0;
    public float scoreMulti = 5;

    void Update() {
        score += Time.deltaTime * scoreMulti;
    }
}

you can use coroutine to update score.

If u want to update score every second, just wait for 1 second and then add 1 to score. Which will mean player is running a distance of 1 unit every second.

You can increase speed of score by decreasing wait time. For example if u want to increase speed upto 2unit/s .Just wait for half a second. Following code updates score every second.

]] IEnumerator Score()
{

  score++;
    // change score GUI
    yield return new WaitForSeconds(1f);
    }]]

Why not just do something like this:

public float time = 1;
public float points = 5;

private float startTime;
private float endTime;

private float score;

void OnEnable() //or "Start"
{
    startTime = Time.time;
}

void OnFinish()
{
    endTime = Time.time;

    score = Mathf.RoundToInt(((endTime - startTime) / time) * points);

    print("player score = " + score);
}

This way you save using “Update” or even a Coroutine.