【关于背包的制作】ScriptableObject类

ScriptableObject类意义

保存对于游戏过程中不变的数据,不用挂载在实例上,而是通过引用而访问数据,能够减少内存使用

ScriptableObject用法

要使用 ScriptableObject,必须在应用程序的 Assets 文件夹中创建一个脚本,并使其继承自 ScriptableObject 类。您可以使用 CreateAssetMenu 属性,从而使用您的类轻松创建自定义资源。

using System.Collections;
using System.Collections.Generic;
using System.IO.Enumeration;
using UnityEngine;

[CreateAssetMenu(fileName = "New Item", menuName = "Inventory/New Item")] //建立菜单栏
public class Item : ScriptableObject
// Start is called before the first frame update
{
    public string itemName;//物品各类属性 名称 图像 数量 介绍 可装备性
    public Sprite itemImage;
    public int itemHeld;
    [TextArea]
    public string itemInfo;
    public bool equip;


}

物品相关

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

[CreateAssetMenu(fileName = "New Inventory", menuName = "Inventory/New Inventory")] //建立菜单栏

public class Inventory : ScriptableObject
// Start is called before the first frame update
{
    public List<Item> itemList = new List<Item>();//物品列表

}

背包相关

使用上述在 Assets 文件夹中创建的脚本,您可以通过导航到 Assets > Create > ScriptableObjects > SpawnManagerScriptableObject 来创建 ScriptableObject 的实例。为新的 ScriptableObject 实例提供有意义的名称并更改值。要使用这些值,必须创建一个引用 ScriptableObject(在本例中为 SpawnManagerScriptableObject)的新脚本。

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

public class ItemInWorld : MonoBehaviour
{
    // Start is called before the first frame update
    public Item thisItem;
    public Inventory myBag;
    public void OnTriggerEnter2D(Collider2D other)
    {
        if (other.gameObject.CompareTag("Player"))//玩家碰到物品就会进入背包然后摧毁原来物品
            {
            AddNewItem();
            
            Destroy(gameObject);
        }
    }
    public void AddNewItem()
    {
        if (!myBag.itemList.Contains(thisItem))
        { myBag.itemList.Add(thisItem);
            InventoryManage.CreateNewItem(thisItem);
        }
        else
            thisItem.itemHeld += 1;
    }

}

将物品从地图放入背包的部分代码,引用前面创建的两个 ScriptableObject

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值