To be honest, you gave very little information about the game. But I will try to come up with some possible scenarios and solutions.
First of all, you stated that this is an endless game, then I don't know what distance are you calculating between the player and a point. So, your code didn't make much sense to me, please explain if I'm missing something.
Now, you said you want to calculate the score based on the distance that the player has traveled on + x-axis. So, take a look at this code:
float previousPlayerX;
public Transform player;
private float score;
void Awake()
{
previousPlayerX= player.position.x;
score = 0;
}
void Update()
{
if (previousPlayerX < player.position.x)
{
score += player.position.x - previousPlayerX;
previousPlayerX = player.transform.position.x
}
}
This code will increase the score as long as the player is running to +x. If the player stops or even turns back, the score will not be updated. Also, note that if your starting position is 0, then you don't need to subtract the two positions to add the score, you can simply go ahead and say score = player.position.x
and it should give you the same result. Furthermore, I would implement this code in a coroutine with a little bit of wait time to avoid possible bugs maybe.
Now, let's think about another scenario. I don't think the character doesn't go to infinity in endless run games, generally, the character object is stable and you kinda make that illusion of endless flow. So, let's say your character's position is not changing actually, but in the game, it seems like your character is running non-stop. In such a case, you may want to increase the score based on the time passing.
private float score;
void Awake()
{
score = 0;
StartCoroutine(UpdateScore());
}
IEnumerator UpdateScore()
{
while(true)
{
score += 1;
yield return new WaitForSeconds(1);
}
}
As you can see in the second code, I'm just assuming that my character runs non-stop and I'm just increasing the score by 1 every second. You can do it in every half a second, you can increase the score by multiplying with a speed value or you can put an if statement and don't increase the score if the character is stunned for example. So, it's all up to you.
I hope that answer helps and gives you a general idea. Let me know in the comments if you have any other questions related to this.