用GUI实现倒计时:

方法一:利用Time.time,这是以秒计算到游戏开始的时间。也就是说,从游戏开始到到现在所用的时间。

代码如下:

using UnityEngine;
using System.Collections;

public class displayTime : MonoBehaviour
{
    //数值
    public string myStringScore;

    public float x = 85;
    public float y = 19;
    public float scale = 1;

    public Color myColor;
    //定义数组
    public Texture[] myNumber = new Texture[10];
    //public Texture Tex;
    //
    private int index = 0;
    private int width = 30;
    private int height = 30;
    public float allTime = 100;
    public float countTime;


    void Start()
    {
        allTime = allTime + Time.time;
    }
    void FixedUpdate()
    {
        countTime = allTime - Time.time;
        //print(countTime);
        myStringScore = countTime.ToString();
        if (countTime <= 0)
        {
            //游戏结束之后进行设置
            countTime = 0;
            //Application.LoadLevelAdditive(4);
            //Application.Quit();//退出游戏
            // print("countTime");
            // return;
        }
        else
        {
            return;
        }
    }

    void Update()
    {

    }

    // Use this for initialization
    void OnGUI()
    {
        GUI.color = myColor;
        if (myStringScore != null)
        {
            for (int i = 0; i < myStringScore.Length; i++)
            {
                if (myStringScore.Substring(i, 1) == ".")
                {
                    break;
                }
                GUI.DrawTexture(new Rect(x + i * scale * width, y, scale * width, scale * height), myNumber[int.Parse(myStringScore.Substring(i, 1))], ScaleMode.StretchToFill, true, 0);
                //GUI.DrawTexture(new Rect(x + i * scale * width, y, scale * width, scale * height),myNumber[myStringScore[i]-48]);
            }
        }
    }
}

绑定代码到Camera上,设置倒计时10个数图片:

unity3d游戏开发 —— 倒计时

 

unity3d游戏开发 —— 倒计时

 


 

 方法二:使用yield return new WaitForSeconds(1);等待1秒

using UnityEngine;
using System.Collections;

public class CoolTime : MonoBehaviour {
    // Use this for initialization
    void Start () {
    }
    int CoolTimes = 100;
    // Update is called once per frame
    void Update () {

    }
    void OnGUI()
    {
        GUILayout.Label(CoolTimes.ToString());
        if (GUILayout.Button("Begin"))
        {
            StartCoroutine(waitForOneSecond());
        }
    }

    public IEnumerator waitForOneSecond()
    {
        while (CoolTimes >= 0)
        {
            CoolTimes--;
            yield return new WaitForSeconds(1);   
        }
    }
}

 

相关文章:

  • 2021-12-27
  • 2021-09-22
  • 2021-09-20
  • 2021-04-24
  • 2022-01-16
  • 2021-08-15
  • 2021-11-16
猜你喜欢
  • 2022-12-23
  • 2021-07-06
  • 2021-06-29
  • 2021-09-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案