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

Unity(C#)销毁GameObject时分数无法累加问题求助

问题原因与修复方案

问题根源

你的treeScore是每个树木GameObject挂载的Harvest脚本的局部变量,每次销毁树木时,该脚本实例也会被一同销毁。新生成的树木是全新的GameObject,附带的Harvest实例中treeScore初始值为0,因此每次点击只会输出1,无法实现跨树木的分数累加。


修复方法(二选一即可)

方法1:使用全局单例分数管理器

创建一个独立的分数管理脚本,确保全局只有一个实例,用来存储和更新总分数:

using UnityEngine;

public class ScoreManager : MonoBehaviour
{
    public static ScoreManager Instance;
    public int totalTreeScore;

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

    public void AddScore(int amount)
    {
        totalTreeScore += amount;
        Debug.Log(totalTreeScore);
    }
}

将这个脚本挂载到一个不会被销毁的GameObject上(比如新建的GameManager空对象),然后修改Harvest脚本的AddTreeScore方法:

void AddTreeScore()
{
    ScoreManager.Instance.AddScore(1);
}

方法2:复用已有Spawner存储分数

既然你已经引用了Spawner脚本,可以直接在Spawner中添加全局分数变量:

// 在Spawner脚本中添加
public int totalTreeScore;

然后修改Harvest的AddTreeScore方法:

void AddTreeScore()
{
    spawnerScript.totalTreeScore++;
    Debug.Log(spawnerScript.totalTreeScore);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 23:32:41