0
点赞
收藏
分享

微信扫一扫

Unity背包系统-2:数据库存储方法ScriptableObject

雅典娜的棒槌 2022-04-07 阅读 57
unity

元素(item)代码:

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

[CreateAssetMenu(fileName ="New Item",menuName ="Inventory/New Item")]
public class Item : ScriptableObject
{
    public string itemName;
    public Sprite image;
    public int itemHold;
    public bool equip;

    [TextArea]
    public string info;
}

数据库代码(ItemList)代码:

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

[CreateAssetMenu(fileName ="New List",menuName ="Inventory/New List")]
public class ItemList : ScriptableObject
{
    public List<Item> itemList = new List<Item>();//item和itemscript的类名一样
}

为了将sprite和数据库,元素连接我们需要在创建一个脚本:

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

public class ItemOnWorld : MonoBehaviour
{
    public Item TheItem;
    public ItemList List;
    // Start is called before the first frame update
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("player"))
        {
            AddNewItem();
            Destroy(gameObject);
        }
    }
    private void AddNewItem()
    {
        if (!List.itemList.Contains(TheItem))
        {
            List.itemList.Add(TheItem);
        }
        else
        {
            TheItem.itemHold++;
        }
    }
}

解释:

冒号在C#中表示继承,ScriptableObject 是一个可独立于类实例来保存大量数据的数据容器。

unity中[]表示具有特殊功能的标记。

[CreateAssetMenuAttribute]对 ScriptableObject 派生类型进行标记,使其自动列在 Assets/Create 子菜单中,以便能够轻松创建该类型的实例并将其作为“.asset”文件存储在项目中。

fileName: 此类型的新建实例使用的默认文件名。
menuName: Assets/Create 菜单中显示的此类型的显示名称。
order: Assets/Create 菜单中菜单项的位置。

效果图:
在这里插入图片描述

ItemOnWorld脚本中成员变量 的类型和Item和ItemList脚本的类相对应

[TextArea]为文本区域

List.itemList.Contains(TheItem)

List为对应的数据库类的实例,而itemList为数据库类的成员变量(真正的数据库),只不过我们对这个成员变量进行了实例化。
参考资料:
CreateAssetMenuAttribute

举报

相关推荐

0 条评论