機能作成にあたり、下記が大変大変参考になりました。感謝!
【参考】UnityでScriptableObjectを使ってアイテムデータベースを作成する
Item.cs
//アイテムの情報を作成する
[Serializable]
[CreateAssetMenu(fileName = "Item", menuName = "CreateItem")]
public class Item : ScriptableObject
{
public enum KindOfItem
{
Weapon,
UseItem
}
// アイテムの種類
[SerializeField]
private KindOfItem kindOfItem;
// アイテムのアイコン
[SerializeField]Sprite icon;
// アイテムの名前
[SerializeField]
private string itemName;
// アイテムの情報
[SerializeField]
private string information;
public KindOfItem GetKindOfItem()
{
return kindOfItem;
}
public Sprite GetIcon()
{
return icon;
}
public string GetItemName()
{
return itemName;
}
public string GetInformation()
{
return information;
}
ItemController.cs
//アイテム取得のためのクラス。
public class ItemController : MonoBehaviour
{
[SerializeField] Item iteminfo; //さっきのアイテム情報をアタッチ
Collider other;
private void Start()
{
this.OnTriggerStayAsObservable()
.Where(other => other.gameObject.tag == "Player")
.Where(_ => PlayersItem.itemLists.Count < 6)
.Where(_ => Input.GetKeyUp(KeyCode.LeftControl))
.Subscribe(_ => AddItem())
.AddTo(this.gameObject);
}
void AddItem(){
PlayersItem.itemLists.Add(iteminfo);
Destroy(this.gameObject);
}
}
PlayersItem.cs
//プレイヤーの所持アイテムはここで管理
using UnityEngine;
using UniRx;
[CreateAssetMenu(fileName = "PlayersItem", menuName = "CreatePlayersItem")]
public class PlayersItem : ScriptableObject
{
public static ReactiveCollection<Item> itemLists = new ReactiveCollection<Item>();
//アイテムリストを返す
public ReactiveCollection<Item> GetItemLists()
{
return itemLists;
}
}
ItemMenue.cs
//所持アイテムをアイテム画面に映す。改良の余地あり
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UniRx;
public class ItemMenue : MonoBehaviour
{
[SerializeField] List<Image> itemSlots = new List<Image>();
// Use this for initialization
void Start()
{
PlayersItem.itemLists.ObserveAdd()
.Subscribe(_ => ReloadItemSlots());
PlayersItem.itemLists.ObserveRemove()
.Subscribe(_ => ReloadItemSlots());
}
void ReloadItemSlots()
{
for (int i = 0; i < PlayersItem.itemLists.Count; i++)
{
itemSlots[i].sprite = PlayersItem.itemLists[i].GetIcon();
}
}
}