So, I’m having an issue in my game where the objects I need to pick up require a reference to the Inventory. However, the Inventory attached to an Inventory GameObject that is a child of a Canvas that is instantiated when the game starts. Is possible to get the reference the object to be picked up needs?
Pictures:
Code 1:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PickUpObject : MonoBehaviour {
[SerializeField] Pickup item;
[SerializeField] Inventory inventory;
[SerializeField] AccessInventory access;
private bool hasEntered;
void Update() {
if (Input.GetKeyDown(KeyCode.F) && hasEntered) {
inventory.AddItem(item);
access.accessInventory();
Destroy(this.gameObject);
}
}
void OnTriggerEnter(Collider other) {
if (other.CompareTag("Player")) {
hasEntered = true;
}
}
}
Code 2:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Inventory : MonoBehaviour {
public static Inventory instance;
[SerializeField] List<Pickup> items;
[SerializeField] Transform itemsParent;
[SerializeField] InventorySlots[] inventorySlots;
private void Awake() {
if (instance == null) {
instance = this;
}
else {
Destroy(this.gameObject);
}
}
private void OnValidate() {
if (itemsParent)
{
inventorySlots = itemsParent.GetComponentsInChildren<InventorySlots>();
}
GetUIUpdate();
}
public bool AddItem(Pickup item) {
if (isFull()) {
return false;
}
items.Add(item);
GetUIUpdate();
return true;
}
public bool RemoveItem(Pickup item) {
if (items.Remove(item)){
GetUIUpdate();
return true;
}
return false;
}
public bool isFull() {
return items.Count >= inventorySlots.Length;
}
void GetUIUpdate() {
int i = 0;
for (; i < items.Count && i < inventorySlots.Length; i++) {
inventorySlots_.item = items*;*_
}
for (; i < inventorySlots.Length; i++) {
inventorySlots*.item = null;*
}
}
public void SaveInventory() {
GlobalController.instance.inventory = inventorySlots;
}
}