Creating inventory system with pickup problem
I tried using the free inventory systems in the asset store, but all of them had errors when I downloaded them so I am trying from videos now. Below I have attached my inventory and pickup code built from Noah Calice's tutorials for 2D games, but I converted it to 3D. I just want to be able to walk up to an object, press a key (or eventually for mobile press a button on the screen) and pickup the item, added to a visual inventory. I have a GUI with three slots available. Can someone tell me what I am doing wrong?
public class Inventory : MonoBehaviour { public bool[] isFull; public GameObject[] slots; }
and then the pickup script
public class Pickup : MonoBehaviour {
private Inventory inventory;
public GameObject itemButton;
// Start is called before the first frame update
void Start()
{
inventory = GameObject.FindGameObjectWithTag("Player").GetComponent<Inventory>();
}
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player")&& Input.GetKeyDown(KeyCode.E))
{
for (int i = 0; i < inventory.slots.Length; i++)
{
if (inventory.isFull[i] == false)
{
//ITEM CAN BE ADDED TO INVENTORY
inventory.isFull[i] = true;
other.gameObject.SetActive(false);
//Instantiate(itemButton, inventory.slots[i].transform, false);
//Destroy(gameObject);
break;
}
}
}
}
}
I was trying to play around with it by commenting a section, but I am still learning to code and could use some advice on how to restructure this to achieve my goal.
Answer by highpockets · Aug 22, 2020 at 11:25 PM
GetKeyDown() returns true on the frame the key was pressed and OnTriggerEnter() will happen the moment that the trigger collider is entered. The chances of the key being pressed down on the exact same frame as the trigger collider is entered is not very good.
An option that you may want to consider is to have a bool that is true only when the player is inside the collider of the PickUp:
private bool _canPickUp = false;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
_canPickUp = true;
}
}
private void OnTriggerExit(Collider other)
{
if(other.gameObject.tag(“Player”)
{
_canPickUp = false;
}
}
void Update()
{
if (Input.GetKeyDown(KeyCode.E))
{
if(_canPickUp)
//Pickup item if inventory is not full
}
}
Your answer
Follow this Question
Related Questions
Adding a prefab to the Item class instance 0 Answers
IPointerEnterHandler and IPointerExitHandler not working 1 Answer
Inventory Master 0 Answers
Argument out of range? 2 Answers
How to make a Inventory Hotbar 0 Answers