Hi everyone-
Just trying to figure out where I messed up on the following code to get a digital clock to work.
I think I’m just missing a “{” somewhere, but can’t see where. Would appreciate an extra set of eyes.
Thanks!
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System;
public class ClockDigital : MonoBehaviour {
private Text textClock;
// Use this for initialization
void Start () {
textClock = GetComponent <Text> ();
}
// Update is called once per frame
void Update () {
DateTime time = DateTime.Now;
string hour = LeadingZero (time.Hour);
string minute = LeadingZero (time.Minute);
string second = LeadingZero (time.Second);
textClock.text = hour + ":" + minute + ":" +
second
}
string LeadingZero (int n){
return n.ToString ().PadLeft (2, '0');
}
}
}
When you try to compile code, it points at the line with error. Also, there’s a hotkey to jump from opening to closing brace and vice versa (Ctrl+}, I believe).
In your case:
public class ClockDigital : MonoBehaviour {
private Text textClock;
// Use this for initialization
void Start () {
textClock = GetComponent <Text> ();
}
// Update is called once per frame
void Update () {
DateTime time = DateTime.Now;
string hour = LeadingZero (time.Hour);
string minute = LeadingZero (time.Minute);
string second = LeadingZero (time.Second);
textClock.text = hour + ":" + minute + ":" +
second //<<-- missing closing semicolon
} //<<-- misaligned brace (not an error)
string LeadingZero (int n){
return n.ToString ().PadLeft (2, '0');
}//<<--extra } brace.
}
}
Should be :
public class ClockDigital : MonoBehaviour {
private Text textClock;
// Use this for initialization
void Start () {
textClock = GetComponent <Text> ();
}
// Update is called once per frame
void Update () {
DateTime time = DateTime.Now;
string hour = LeadingZero (time.Hour);
string minute = LeadingZero (time.Minute);
string second = LeadingZero (time.Second);
textClock.text = hour + ":" + minute + ":" + second;
}
string LeadingZero (int n){
return n.ToString ().PadLeft (2, '0');
}
}
And that’s without checking validity of your code.
All things considered, it looks like you’re reinventing the wheel and should familiarize yourself with string.Format function: