- Home /
How to display counter
I have this code which makes a counter, that adds 1 to an integer every 30 minute. Now i would like to display this counter in my main menu scene so that you can see how much time there is to next "energy", how would i do this ?
Here is the code.
static var energyObj : int = 5;
var counter : float;
function Update () {
counter += Time.deltaTime;
if(counter > 1800){
energyObj += 1;
counter = 0.0;
Debug.Log("Energy is " + energyObj);
}
Answer by Destran · Mar 23, 2014 at 03:50 PM
If you wanted to to display how much energy they have.
/ String Content example /
// JavaScript
function OnGUI () {
GUI.Label (Rect (0,0,100,50), "You have: " + energyObj + " Energy");
}
// C#
using UnityEngine;
using System.Collections;
public class GUITest : MonoBehaviour {
void OnGUI () {
GUI.Label (new Rect (0,0,100,50), "You have: " + energyObj + " Energy");
}
}
If you wanted to display the time on the counter
I would change your script so that it's counting down, not up. Because you know, that's how it normally is with cooldowns. EX:
var counter: float;
function Start()
{
counter = 1800;
}
function Update () {
counter -= Time.deltaTime;
if(counter <= 0){
energyObj += 1;
counter = 1800;
Debug.Log("Energy is " + energyObj);
}
And to display that:
/* String Content example */
// JavaScript
function OnGUI () {
GUI.Label (Rect (0,0,100,50), "Time left: " + counter);
}
// C#
using UnityEngine;
using System.Collections;
public class GUITest : MonoBehaviour {
void OnGUI () {
GUI.Label (new Rect (0,0,100,50), "Time left: " + counter);
}
}
This is pretty much taken word for word from:
http://docs.unity3d.com/Documentation/Components/gui-Basics.html
It's a very informative resource and will probably answer most of your display (GUI) questions! :D Hope this helps.
If you want your timer to display in a nicer format i.e( mm:ss) check this out:
http://answers.unity3d.com/questions/45676/making-a-timer-0000-$$anonymous$$utes-and-seconds.html
Now obviously you can't copy paste, but getting it to work for your situation shouldn't be to hard.