Home > Back-end >  How to change a text component to a string in Unity
How to change a text component to a string in Unity

Time:12-24

I am a beginner developer and I am trying to create a timer that shows how many seconds have passed since the start of the game on Unity. I want to change the text component (I am using TextMeshPro to be specific) of the object with the script.

I have been searching on google but nothing has worked yet. I can't find a way to link the public Text to the text component, and I get an error because the text is null.

CodePudding user response:

Well you should reference the text in your code and then change it with a coroutine

public class Timer : MonoBehaviour 
{
   [SerializeField]
   private TMP_Text textComponent;
   private int seconds = 0;

   private IEnumerator TimeRoutine()
   {
      while(Application.isPlaying)
      {
         textComponent.text = seconds.ToString();
         yield return new WaitForSeconds(1f);
         seconds  ;
      }
   }
   
   private void Start()
   {
      StartCoroutine(nameof(TimeRoutine));
   }
}

CodePudding user response:

Code for Timer with Text mesh pro

using UnityEngine;
using TMPro;

public class Timerexample : MonoBehaviour
{

float cntdnw = 30.0f;
public TMP_Text disvar;

void Update() 
{     
  if(cntdnw>0)     
  {         
    cntdnw -= Time.deltaTime;     
  }     
  double b = System.Math.Round (cntdnw, 2);     
  disvar.text = b.ToString ();     
  if(cntdnw < 0)     
  {         
    Debug.Log ("Completed");     
  } 
}
}

Source: Unity timer

  • Related