How to display a variable from the console on the GUI?

Hello,i m using the script below to calculate the distance between me(the player) and an enemy.The distance is shown in the console but i want to see it ingame.How do i do this?

using System.Collections;

public class distance : MonoBehaviour {
    public Transform OneTransform;
    public Transform AnotherTransform;
    // Use this for initialization
    void Start () {

   
    }
   
    // Update is called once per frame
        void Update() {
            if (OneTransform) {
                float dist = Vector3.Distance(OneTransform.position, AnotherTransform.position);
                print("Distance to enemy in m: " + dist);
            }
    }
}

Create a Canvas (GameObject > UI > Canvas) and a Text element (GameObject > UI > Text).

Then change your script to:

using UnityEngine;
using System.Collections;
   
public class distance : MonoBehaviour {

  public Transform OneTransform;
  public Transform AnotherTransform;
  public UnityEngine.UI.Text distLabel; // <-- Assign the Text element in the Inspector view.

  // Update is called once per frame
  void Update() {
    if (OneTransform) {
      float dist = Vector3.Distance(OneTransform.position, AnotherTransform.position);
      print("Distance to enemy in m: " + dist);
      distLabel.text = dist.ToString();
    }
  }
}

Also watch these: Unity UI Tutorials

1 Like

You are very helpfull,the script is working perfectly,thanks a lot!

Glad I could help!