unity3d游戲開發 —— 倒計時


用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個數圖片:

 

 


 

 方法二:使用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);   
        }
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM