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

如何解决Unity场景重加载后已销毁物品重新生成的问题

问题描述

期望实现效果:点击物品后销毁该物品,并将其添加至玩家背包;
当前存在问题:物品被销毁后,重新进入同一场景时,已销毁的物品会重新生成,导致玩家可重复拾取同一物品。

当前代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GetItem : MonoBehaviour
{

    public item thisItem;
    public inventory playerBag;

    private void OnMouseDown()
    {
        AddNewItem();
        Debug.Log(+1);

        DontDestroyOnLoad(gameObject);
        Destroy(gameObject);
    }

    public void AddNewItem()
    {

        if (!playerBag.itemList.Contains(thisItem))
        {
            playerBag.itemList.Add(thisItem);
        }
        else
        {
            thisItem.itemHeld += 1;
        }
        inventorymanager.RefreshItem();
    }
}

问题原因

当前代码仅在拾取时销毁物品,但未持久化记录该物品的拾取状态。场景重新加载时,场景内所有物体会重新实例化,因此之前销毁的物品会再次出现。

解决方案

1. 给物品添加唯一标识

在item类中新增唯一ID字段,用于区分不同物品:

[System.Serializable]
public class item
{
    public string itemName;
    public int itemID; // 每个物品的唯一ID,需确保全局唯一
    public int itemHeld;
    // 其他原有字段...
}

2. 拾取时记录状态,场景加载时验证

修改GetItem脚本,在场景启动时检查物品是否已被拾取,若已拾取则直接销毁;拾取时记录该物品的ID到持久化存储中:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GetItem : MonoBehaviour
{
    public item thisItem;
    public inventory playerBag;

    private void Start()
    {
        // 场景加载时检查该物品是否已被拾取
        if (PlayerPrefs.HasKey("PickedItem_" + thisItem.itemID))
        {
            Destroy(gameObject);
            return;
        }
    }

    private void OnMouseDown()
    {
        AddNewItem();
        Debug.Log("物品已添加至背包");

        // 持久化记录该物品已拾取
        PlayerPrefs.SetInt("PickedItem_" + thisItem.itemID, 1);
        PlayerPrefs.Save();

        Destroy(gameObject);
    }

    public void AddNewItem()
    {
        if (!playerBag.itemList.Contains(thisItem))
        {
            playerBag.itemList.Add(thisItem);
        }
        else
        {
            thisItem.itemHeld += 1;
        }
        inventorymanager.RefreshItem();
    }
}

3. 补充说明

  • 若需要重置拾取状态,可调用PlayerPrefs.DeleteKey("PickedItem_" + thisItem.itemID)删除单条记录,或PlayerPrefs.DeleteAll()清除所有记录。
  • 若物品系统较复杂,建议使用ScriptableObject存储全局已拾取物品列表,或通过JSON序列化将数据写入本地文件,比PlayerPrefs更灵活可控。
  • 若背包需要跨场景保留,需确保playerBag所在的游戏对象通过DontDestroyOnLoad标记为不销毁,或同步将背包数据持久化存储。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 11:17:32