Question by
apoorvlathey · Apr 21, 2016 at 08:43 AM ·
uitexttimerroll a ball
Display timer to Roll a Ball Tutorial
I added the timer to Roll a Ball tutorial that calculates how much time the player took to finish the game. Here is the code :
using UnityEngine; using System.Collections; using UnityEngine.UI;
public class PlayerController : MonoBehaviour {
public float speed;
public float force;
public Text countText;
public Text winText;
float myTime = 0f;
int timertext = myTime as int;
private Rigidbody rb;
private int count;
void Start ()
{
rb = GetComponent<Rigidbody> ();
count = 0;
SetCountText ();
winText.text = "";
}
void Update ()
{
myTime += Time.deltaTime;
if (count < 12) {
myTime += Time.deltaTime;
}
}
void FixedUpdate ()
{
if (SystemInfo.deviceType == DeviceType.Desktop) {
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (movement * speed);
}
else
{
Vector3 movement = new Vector3 (Input.acceleration.x, 0.0f, Input.acceleration.y);
// Adding force to rigidbody
GetComponent<Rigidbody>().AddForce(movement * speed);
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag ("Pick Up")) {
other.gameObject.SetActive (false);
count = count + 1;
SetCountText ();
}
}
void SetCountText ()
{
countText.text = "Score : " + count.ToString ();
if (count >= 12) {
winText.text = " You WIN !!!";
}
}
}
how can i display "myTime" to text ui gameobject ? I am a noob, so please help. :)
Comment
Answer by yapaysinek · Apr 21, 2016 at 10:26 AM
Just add this to your existing script and you are good to go! :)
public Text timer;
void Update () {
timer.text = myTime.ToString ();
}
thanks for your help. Improved version that worked :
void Update () { if (count < 12) { myTime += Time.deltaTime; } else { timer.text = myTime.ToString (); }
timer.text = myTime.ToString ();
}
Currently the timer has about 7 decimals, how can i limit it to just 2 places ?