Unityの2Dゲームで簡単なアイテム欄(インベントリ)の実装Part2です。
はじめに
前回のPart1では「アイテムを移動する」ところまで実装しました。
今回は「アイテムの使用」を実装します。
実装開始
前回のPart1からの続きです。
アイテム効果
まずは適当にアイテムに効果を付けるので「RedCapsule」と言う名前でスクリプトを追加。

スクリプトの中身を下記に変更します。
プレイヤーを赤色に変化させたらアイテムが消えるという感じです。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RedCapsule : MonoBehaviour { private SpriteRenderer Player; void Start() { Player = GameObject.FindGameObjectWithTag("Player").GetComponent <SpriteRenderer>(); } public void Use() { Player.color = Color.red; Destroy(gameObject); } }
クリック時に動作するように指定します。

このままだと、アイテム欄に無い状態で「アイテムをクリック」できてしまうので、スクリプトを変更。
ボタンを移動後に有効にする感じです。
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ItemGet : MonoBehaviour { private void Awake() { gameObject.GetComponent<Button>().enabled = false; } private void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Player")) { transform.position = ItemInventory.instance.ItemSlots.transform.position; gameObject.GetComponent<Button>().enabled = true; } } }
これで実際に動かして、アイテム欄に入った後にクリックしてプレイヤーの色が変わればOK
複数アイテムに対応
現状だとアイテム欄が一つだけなので複数のアイテム欄を作成していきます。
まずはItemSetをコピーして位置を変更して並べます。

スクリプトを下記の様に変更。
アイテム欄を配列にして、アイテム欄にアイテムが入っているかを管理する変数も追加。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ItemInventory : MonoBehaviour { public bool[] isItem; public GameObject[] ItemSlots; public static ItemInventory instance { get; private set; } private void Awake() { instance = this; } }
アイテムを拾った時のスクリプトは空きのアイテム欄を探して、そこに移動するように変更。
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ItemGet : MonoBehaviour { public int ArrayNo { get; private set; } private void Awake() { gameObject.GetComponent<Button>().enabled = false; } private void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Player")) { for (int i = 0; i < ItemInventory.instance.isItem.Length; i++) { if (ItemInventory.instance.isItem[i] == false) { MoveItem(i); break; } } } } private void MoveItem(int i) { ArrayNo = i; ItemInventory.instance.isItem[i] = true; transform.position = ItemInventory.instance.ItemSlots[i].transform.position; gameObject.GetComponent<Button>().enabled = true; } }
アイテムを使用した時に、該当するアイテム欄のフラグをあけます。
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RedCapsule : MonoBehaviour { private SpriteRenderer Player; void Start() { Player = GameObject.FindGameObjectWithTag("Player").GetComponent <SpriteRenderer>(); } public void Use() { int i = gameObject.GetComponent<ItemGet>().ArrayNo; ItemInventory.instance.isItem[i] = false; Player.color = Color.red; Destroy(gameObject); } }
後は変数にセットすれば完成。

適当にアイテムを増やして動くか確認。

実際はアイテムをプレハブ化して、アイテム取得時にアイテム欄の配下にインスタンス化して、配下にアイテムがあるか無いかでアイテム欄が使えるか判断する。とかの方が、管理はしやすいのかも。
とりあえず「超簡単なアイテム欄」って感じです。