You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# Unity游戏开发:如何实现每秒累计0.01分的百分秒计数

实现调整方案

必要改动点

  • 首先确认score变量定义为浮点类型(float/double),如果之前定义为int整数类型,小数增量会被自动截断,无法实现累计效果
  • 将分数增量的系数从1替换为0.01f,即可实现每秒累计增加0.01分的效果
  • 根据显示需求调整文本赋值逻辑

代码示例

版本1:显示两位小数分数

// 提前定义score为float类型,示例:public float score = 0f;
// Update is called once per frame
void Update()
{
    if(GameObject.FindGameObjectWithTag("Player") != null)
    {
        score += 0.01f * Time.deltaTime;
        scoreText.text = score.ToString("F2");
    }
}

版本2:仅显示整数分数(满1分才更新显示)

// 提前定义score为float类型,示例:public float score = 0f;
// Update is called once per frame
void Update()
{
    if(GameObject.FindGameObjectWithTag("Player") != null)
    {
        score += 0.01f * Time.deltaTime;
        scoreText.text = ((int)score).ToString();
    }
}

可选优化

小提示:不要在Update生命周期中反复执行GameObject.FindGameObjectWithTag查找操作,可以在Start方法中提前缓存Player对象引用,降低不必要的性能消耗


内容的提问来源于stack exchange,提问作者Gidds R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 09:30:04