- Home /
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.
Answer by Rtyper · Mar 13, 2015 at 04:42 PM
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 am using the new UI, could you show me how it's dont there? I've watched all videos about it, but still struggling a little
You would add a Label object into your scene and position it where you want on the screen to use as your score readout.
Then in your script add using UnityEngine.UI to the top, and add a Label variable that you'd reference and set from the script, using something like this:
public Text label;
void score(){
distance = Vector3.Distance (player.position, transform.position);
label.text = distance.ToString ();
}
Answer by maccabbe · Mar 13, 2015 at 04:47 PM
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());
}
}
http://docs.unity3d.com/ScriptReference/GUI.html
2) Use the New UI. This is mostly done in the inspector.
http://unity3d.com/learn/tutorials/modules/beginner/live-training-archive/the-new-ui
3) Use a Text Mesh (Mesh->Text Mesh)
Your answer
![](https://koobas.hobune.stream/wayback/20220613190022im_/https://answers.unity.com/themes/thub/images/avi.jpg)