在脚本文件夹中创建一个新的文件夹,命名为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个齿轮子弹时,数据库显示如下