Hi, I’m trying to make a functions that allows stacking inside my slotList.
Whenever I try to pickup an object I get this error:
This is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour
{
public GameObject inventoryPrefab;
public GameObject inventoryUI;
public List<InventorySlot> slotList = new List<InventorySlot>();
void Start()
{
}
void Update()
{
}
public void AddToInventory(Item _item, int _amount)
{
for (int i = 0; i < slotList.Count; i++)
{
if (_item.isStackable && _item.id == slotList[i].item.id)
{
slotList[i].AddAmount(_amount);
return;
}
else if(_item.id != slotList[i].item.id)
{
//print("false");
}
}
slotList.Add(new InventorySlot(_item, _amount));
}
//public void CreateDisplay()
//{
// for (int i = 0; i < slotList.Count; i++)
// {
// var obj = Instantiate(inventoryPrefab, inventoryUI.transform);
// }
//}
//public void UpdateDisplay()
//{
//}
}
and this is the InventorySlot script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InventorySlot : MonoBehaviour
{
public Item item;
public int amount;
public InventorySlot(Item _item, int _amount)
{
item = _item;
amount = _amount;
}
public void AddAmount(int Value)
{
amount += Value;
}
}
and this is the interaction script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InteractRay : MonoBehaviour
{
public Camera playerCam;
public float rayRange = 2f;
public Inventory inventory;
void Start()
{
}
void Update()
{
InteractionRay();
}
public void InteractionRay()
{
RaycastHit hit;
//Debug.DrawRay(playerCam.transform.position, playerCam.transform.forward * 2, Color.red, 0.5f);
if (Physics.Raycast(playerCam.transform.position, playerCam.transform.forward, out hit, rayRange))
{
//print(hit.transform.name);
if (hit.transform.tag == "Item")
{
if (Input.GetKeyDown(KeyCode.F))
{
if (hit.transform.GetComponent<GroundItem>().item)
{
inventory.AddToInventory(hit.transform.GetComponent<GroundItem>().item, hit.transform.GetComponent<GroundItem>().amount);
}
//GetComponent<Inventory>().AddToInventory(hit.transform.GetComponent<GroundItem>().item);
Destroy(hit.transform.gameObject);
}
}
}
}
}
the error happens on the following line: inventory.AddToInventory(hit.transform.GetComponent().item, hit.transform.GetComponent().amount);
I don’t know how to fix this.