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

Unity水果切割游戏仅首次碰撞更新分数问题求助

水果切割游戏分数无法累加的解决方案

问题根源

你的代码里每个水果对象都持有独立的currentScore变量,并非全局共享的分数。切第一个水果时,它的currentScore从0变为10并显示;切第二个水果时,新水果的currentScore初始为0,加10后还是10,覆盖UI文本后看起来分数没涨。

修复步骤

1. 创建全局分数管理单例(GameManager)

这个脚本负责存储全局分数,确保所有水果操作同一个分数值:

using UnityEngine;
using TMPro;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;
    public TextMeshProUGUI scoreText;
    public int currentScore = 0;

    void Awake()
    {
        // 单例模式保证全局唯一
        if (Instance == null)
            Instance = this;
        else
            Destroy(gameObject);
    }

    public void AddScore(int amount)
    {
        currentScore += amount;
        UpdateScoreText();
    }

    void UpdateScoreText()
    {
        scoreText.text = $"Score: {currentScore}";
    }
}

2. 修改FruitCutter脚本

移除自身的分数变量,改为调用GameManager的全局分数更新方法:

using UnityEngine;

public class FruitCutter : MonoBehaviour
{
    public GameObject halfFruitPrefab;
    public AudioClip sliceSound;

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Knife"))
        {
            AudioSource.PlayClipAtPoint(sliceSound, transform.position);
            
            // 调用全局分数累加
            GameManager.Instance.AddScore(10);

            Instantiate(halfFruitPrefab, transform.position, transform.rotation);
            Instantiate(halfFruitPrefab, transform.position, transform.rotation);

            gameObject.SetActive(false);
        }
    }
}

3. 场景配置

  • 在场景中新建空物体,命名为GameManager,挂载上述GameManager脚本
  • 将UI的scoreText拖到GameManager组件的scoreText字段上
  • 确保所有水果的FruitCutter脚本不再绑定scoreText,只保留halfFruitPrefab和sliceSound的引用

额外检查点

  • 确认刀具和水果的Collider都勾选了Is Trigger(或碰撞体交互设置正确)
  • 水果被SetActive(false)后,不会重复触发碰撞(避免重复加分)

内容的提问来源于stack exchange,提问作者thisis-sandeep

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:25:11