J'essaye de réalisé un système d'inventaire qui utilise des scriptables objects:
Des scriptable objects qui représentent les items dans l'inventaire:
Code : Tout sélectionner
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName ="New Item", menuName ="Inventory/Items")]
public class InventoryItem : ScriptableObject
{
public string itemName;
public string itemDescription;
public Sprite itemImage;
public int numberHeld;
public bool usable;
public bool unique;
}
Et un qui représente cette inventaire:
Code : Tout sélectionner
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Inventory", menuName = "Inventory/Player Inventory")]
public class PlayerInventory : ScriptableObject
{
public List<InventoryItem> myInventory = new List<InventoryItem>();
}
J'arrive a représenter correctement ceux-ci en utilisant un bouton en préfab "ButtonBlankSpot" constitué d'une image et d'un texte qui sont remplacer par l'image et le nombre d'objet.
Grace aux scripts suivants:
Code : Tout sélectionner
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class InventorySlot : MonoBehaviour
{
[Header("UI Stuff to change")]
[SerializeField] private TextMeshProUGUI itemNumberText;
[SerializeField] private Image itemImage;
[Header("Variable from the item")]
public InventoryItem thisItem;
public InventoryManager thisManager;
public void Setup(InventoryItem newItem, InventoryManager newManager)
{
thisItem = newItem;
thisManager = newManager;
if(thisItem)
{
itemImage.sprite = thisItem.itemImage;
itemNumberText.text = ""+thisItem.numberHeld;
}
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
Code : Tout sélectionner
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.InputSystem;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class InventoryManager : MonoBehaviour
{
[Header("Inventory Information")]
public PlayerInventory playerInventory;
[SerializeField] private GameObject blankInventorySlot;
[SerializeField] private GameObject inventoryPanel;
[SerializeField] private TextMeshProUGUI descriptionText;
// Start is called before the first frame update
void Start()
{
MakeInventorySlots();
}
private void Awake()
{
}
// Update is called once per frame
void Update()
{
}
void MakeInventorySlots()
{
if (playerInventory)
{
for (int i = 0; i < playerInventory.myInventory.Count; i++)
{
GameObject temp = Instantiate(blankInventorySlot, inventoryPanel.transform.position, Quaternion.identity);
temp.transform.SetParent(inventoryPanel.transform);
temp.transform.localScale = new Vector3(1, 1, 1);
InventorySlot newSlot = temp.GetComponent<InventorySlot>();
if (newSlot)
{
newSlot.Setup(playerInventory.myInventory[i], this);
}
}
}
}
}