从字符串到浮点数的 TryParse 不会给出结果



嘿伙计们,我知道它已经被覆盖了很多,我到处寻找并尝试了一切,我正在制作一个游戏,其中高分应该保存为最高分,为此我需要将字符串变成浮点数作为关卡的最后时间,以检查它是否是最高分,但当我这样做时,我得到的只是 0, 我在代码中放置了两个调试以查看我得到的内容,我认为刺痛是最后一次,但浮点为 0。 我知道我的代码真的很糟糕,这是我尝试制作的第一个游戏,但我坚持了数周。 我用线条标记了我的问题,请帮助我!!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Globalization;
public class Timer : MonoBehaviour
{
public string strTag;
public Text timerText;
private float finalTime;
private float startTime;
// Start is called before the first frame update
void Start()
{
startTime = Time.time;
}
// Update is called once per frame
void Update()
{
float t = Time.time - startTime;
string minutes = ((int)t / 60).ToString();
string seconds = (t % 60).ToString("f2");
timerText.text = minutes + ":" + seconds;
}

private void OnCollisionEnter(Collision collision)
{
if (collision.collider.tag == strTag)
{
--------------------------------------------------------
string finalTimeStr = timerText.text;
float.TryParse(finalTimeStr, NumberStyles.Any, 
CultureInfo.InvariantCulture, out finalTime);    
Debug.Log(finalTimeStr);
Debug.Log(finalTime);
--------------------------------------------------------

if (finalTime > 0 && finalTime < PlayerPrefs.GetFloat("bestTime" 
+ SceneManager.GetActiveScene().buildIndex, 9999))
{
PlayerPrefs.SetFloat("bestTime" + 
SceneManager.GetActiveScene().buildIndex, finalTime);
int Check = 0;
Check = PlayerPrefs.GetInt("Check" + 
SceneManager.GetActiveScene().buildIndex, 0);
Debug.Log(Check);
if (PlayerPrefs.GetFloat("bestTime" + 
SceneManager.GetActiveScene().buildIndex, 9999) < 40 && Check == 0)
{
Check++;
PlayerPrefs.SetInt("Stars" + 
SceneManager.GetActiveScene().buildIndex, 1);
Debug.Log(string.Format("{0:N3}", 
PlayerPrefs.GetFloat("bestTime" + 
SceneManager.GetActiveScene().buildIndex, 9999)));
}
if (PlayerPrefs.GetFloat("bestTime" + 
SceneManager.GetActiveScene().buildIndex, 9999) < 30 && Check == 1)
{
Check++;
PlayerPrefs.SetInt("Stars" + 
SceneManager.GetActiveScene().buildIndex, 1);
}
if (PlayerPrefs.GetFloat("bestTime" + 
SceneManager.GetActiveScene().buildIndex, 9999) < 25 && Check == 2)
{
Check++;
PlayerPrefs.SetInt("Stars" + 
SceneManager.GetActiveScene().buildIndex, 1);
}
PlayerPrefs.SetInt("Check" + 
SceneManager.GetActiveScene().buildIndex, Check);
}
}
}
}

如果必须使用字符串来存储时间,您可能会考虑的一件事是使用Timespan类来创建string值并将其解析为float值和从中解析

// This format is for one or two digit minutes and two digit seconds
const string timeFormat = "m\:ss";
// Get the elapsed seconds
float t = Time.time - startTime;
// Display the seconds as a formatted string
timerText.text = TimeSpan.FromSeconds(t).ToString(timeFormat);
// Get the total number of seconds from the formatted time string
float finalTime = (float)TimeSpan.ParseExact(timerText.text, timeFormat, 
CultureInfo.CurrentCulture).TotalSeconds;

最新更新