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