distance based score system

I have an infinity platformer and I’d like to count distance traveled, got this code:
using UnityEngine;
using System.Collections;

public class DistanceSystem : MonoBehaviour {

	public float distance;
	public Transform player;


	void Awake () {
		distance = Vector3.Distance (player.position, transform.position);

	}
	
	// Update is called once per frame
	void Update () {
		score ();

	}
	void score(){
		distance = Vector3.Distance (player.position, transform.position);
		distance.ToString ();

	}
}

how do i display this on a text field? and when i print the value of distance it shows 500 at start, i want the starting point to be 0.

One easiest way to set the starting distance to be 0 is to initialize the position of the distance system gameObject to the player’s starting position. You can also use a Vector3 variable to store the player’s starting position.

There are also few ways to display the information as a text field.

  1. Use the GUI class

    public class DistanceSystem : MonoBehaviour {
    public float distance;
    public Transform player;

     void Start() {
         transform.position=player.position;
         distance=0;
     }
     void Update() {
         distance=Vector3.Distance(player.position, transform.position);
     }
     void OnGUI() {
         GUI.Label(new Rect(10, 10, 100, 20), distance.ToString());
     }
    

    }

  1. Use the New UI. This is mostly done in the inspector.
  1. Use a Text Mesh (Mesh->Text Mesh)

The position of the object you have this on is 500 units away from your player object at the start. Make sure they start in the same location and distance will be 0 at the start. Alternatively, you could store the starting distance in a variable, and take that away from Vector3.Distance (player.position, transform.position) when setting the distance variable.

Displaying it depends on how you want to do the HUD/GUI for your game. The best option would probably be the new UI system if you’re using 4.6 / 5, or the OnGUI system pre 4.6. Either way, there are plenty of tutorials out there for both. Have a look at these:

I upvote your reply @maccabbe
it’s simple and really good with the various solutions
but just for the gui, not bad to note the color option
like for exemple GUI.color = Color.black;