unity背包系统之背包里部数据的存储

在脚本文件夹中创建一个新的文件夹,命名为Storage

 要想做一个背包系统,可以分为:不同的背包,不同的items

所以再创建两个文件夹,分别命名为GoodsItem,Inventory

在GoodsItem中添加一个GoodsItem脚本

 代码如下,其中fileName ="New GoodsItem",menuName ="Inventory/New GoodItem"代表New GoodItem为Inventory的子菜单,通过GoodItem创建出来的对象名叫做New GoodsItem

且GoodsItem继承自ScriptableObject

[CreateAssetMenu(fileName ="New GoodsItem",menuName ="Inventory/New GoodItem")] 
public class GoodsItem : ScriptableObject
{
    public string itemName;
    public Sprite itemSprite;
    public int itemHeld;
    [TextArea]
    public string itemInfo;    
}

接下来就可以创建相应的对象了,把它命名为齿轮子弹

如图,可以给它添加上一些信息

接下来是同理,创建一个背包脚本,命名为Inventory

[CreateAssetMenu(fileName ="New Inventory",menuName ="Inventory/New Inventory")]
public class Inventory : ScriptableObject
{
    public List<GoodsItem> GoodsItems = new List<GoodsItem>(); 
}

 现在就可以创建一个Inventory了,将它命名为GoodsBag

接下来放几个齿轮子弹到游戏场景中,并为它们添加上碰撞组件

接下来要写一个脚本连接齿轮子弹和数据库,将它命名为GoodsOnWorld

public class GoodsOnWorld : MonoBehaviour
{
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.CompareTag("Ruby"))
        {
            AddNewItem();
            Destroy(gameObject); 
        }
    }

    public GoodsItem thisItem;
    public Inventory thisInventory;
    public void AddNewItem()
    {
        if(!thisInventory.GoodsItems.Contains(thisItem))
        {
            thisInventory.GoodsItems.Add(thisItem);
            thisItem.itemHeld++;//物品持有数量
        }    //如果持有这个物品,则物品不要添加,而是让数量加1
        else
        {
            thisItem.itemHeld++;
        }
    }
}

 之后把这个脚本添加到齿轮子弹上,当玩家接触到1个齿轮子弹时,数据库显示如下

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值