【Unity3d】学习笔记(9)——写一个计时器工具

来源:互联网 发布:linux oracle em打不开 编辑:程序博客网 时间:2024/06/06 07:37

今天看到一个Unity3D的机试题:
写一个计时器工具,从整点开始计时,格式为:00:00:00
于是试着实现了一下。
创建工程后添加一个Cube物体,为其添加一个脚本。

using UnityEngine;using System.Collections;public class Cube : MonoBehaviour {    private float timer = 0f;    private int h = 0;    private int m = 0;    private int s = 0;    private string timeStr = string.Empty;    // Update is called once per frame    void Update () {        timer += Time.deltaTime;        if (timer >= 1f) {            s++;            timer = 0;        }        if (s >= 60) {            m++;            s = 0;        }        if (m >= 60) {            h++;            m = 0;        }        if (h >= 99) {            h = 0;        }    }    void OnGUI(){        timeStr = string.Format ("{0:D2}:{1:D2}:{2:D2}", h, m, s);        GUI.Label (new Rect (10, 10, 100, 200), timeStr);    }}

运行之后就能看到计时效果了。
这里写图片描述
利用一个计时器就能做到。需要注意的是h大于99之后要归0。如果是完成一个时钟的话,这里改成24就行了。

0 0
原创粉丝点击