嗨,我剛剛開始學習代碼。我在unity中創建了一個游戲,我的分數在游戲的每一秒鐘都要計算 1。我正在為如何每秒計算0.01而苦惱。
//Update is called once per frame。
void Update()
{
if(GameObject.FindGameObjectWithTag("Player") != null)
{
score = 1 * Time.deltaTime;
scoreText.text = ((int)score).ToString()。
}
}
uj5u.com熱心網友回復:
我認為做相反的事情會更容易。 你將把你的分數設定為已經過去的時間。
private int StartTime。
void Awake()
{
if(GameObject.FindGameObjectWithTag("Player") != null)
{
StartTime = Time.time。
}
}
void Update()
{
if(GameObject.FindGameObjectWithTag("Player") != null)
{
score = StartTime - Time.time;
scoreText.text = ((int)score).ToString()。
}
uj5u.com熱心網友回復:
為什么不簡單地做
void Update()
{
if(GameObject.FindGameObjectWithTag("Player") != null)
{
score = 0.01f * Time.deltaTime;
scoreText.text = ((int)score).ToString()。
}
uj5u.com熱心網友回復:
這個腳本也許能幫助你。請看這個
using System;
using TMPro;
using UnityEngine;
public class TimeCounter : MonoBehaviour {
[][Space(5)]
[] private float timeInMin。
private float tickTime;
private float timeinSec;
public event EventHandler OnTimeOver;// On Time Over
private TextMeshProUGUI timeCounterTextMesh;
public static TimeCounter instance { get; private set; }
// Const
private const float RESET_TIME = 0f;
private const float STD_TIMECONV = 60f;
。
// On Awake
private void Awake(){
instance = this;
}
//On Start; }
private void Start() {
SetTimer()。
}
//On Update。
private void Update(){
CountTime()。
}
。
private void SetTimer(){
if (timeInMin >= 1){
SetTimer_NotUnderOne()。
} else{
SetTimer_UnderOne()。
}
}
//計數時間。
private void CountTime() {
tickTime -= Time.deltaTime;// counting Sec
if (tickTime <= RESET_TIME){
tickTime = STD_TIMECONV; // Reset Sec
if (timeInMin > RESET_TIME)
timeInMin--。
else TimeOver();// Game Over
}
//Displaying Time //Displaying Time }
Debug.Log("Min : " timeInMin " Sec : " (int)(tickTime)) 。
}
。
private void SetTimer_NotUnderOne(){
if (IsFloat(timeInMin)) { // Number is Float
timeinSec = timeInMin * STD_TIMECONV;// Min to Sec
float _timeInSec = (int)timeInMin * STD_TIMECONV;/Min to Sec
!"FloatingPoint
timeinSec -= _timeInSec;//獲得剩余秒數。
timeInMin = (int)timeInMin;//忽略浮點。
tickTime = timeinSec;
}
else{ //Number is Int; }
timeInMin--。
//設定默認秒數為60秒。
tickTime = STD_TIMECONV;
}
}
private void SetTimer_UnderOne(){
tickTime = timeInMin * STD_TIMECONV;
//設定最小值為零。
timeInMin = RESET_TIME。
}
private bool IsFloat title">IsFloat(float Value) => ((int)Value - Value ! =0)。)
// On Time Over
private void TimeOver(){
OnTimeOver?.Invoke(this, EventArgs.Empty) 。
DestorySelf()。
}
//銷毀自我。
private void DestorySelf(){
Destroy(gameObject.GetComponent<TimeCounter>())。
}
。
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/312676.html
標籤:
