I am working on a game, and I got stuck on a problem.
I want my game to allow the player to pick up items anywhere around the player, and I have a icon to indicate which item the player is going to pick up.
I have a box collider as a trigger for the item object, when the player is in the box collider trigger area, it will show the pickup icon, but if there is multiple items it just logged a bunch of errors about object reference not set to an instance of an object and not letting the player pick up anything.
Is there any way to get the closest item, showing the icon on it and allowing the player to pick it up?
Here is my code for the Item Pickup: (Note I created a ScriptableObject Script for “ItemScriptable”)
This is also asked on Unity Answers but I got no response after a week.
Item.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Item : MonoBehaviour
{
public ItemScriptable item;
private GameObject PickupIcon;
private BoxCollider itemRange;
private AudioSource pickupSound;
void Awake()
{
PickupIcon = GameObject.Find(“Canvas/PickupIcon”);
itemRange = GetComponentInChildren();
pickupSound = GameObject.Find(“Player/PickupSound”).GetComponent();
PickupIcon.SetActive(false);
}
void OnTriggerEnter(Collider item)
{
if (item.gameObject.tag == “Player”)
{
PickupIcon.SetActive(true);
}
}
void OnTriggerStay(Collider item)
{
if (item.gameObject.tag == “Player”)
{
Vector3 icoPos = Camera.main.WorldToScreenPoint(this.transform.position);
PickupIcon.transform.position = icoPos;
CheckForPickup();
}
}
void OnTriggerExit(Collider item)
{
if (item.gameObject.tag == “Player”)
{
PickupIcon.SetActive(false);
}
}
void CheckForPickup()
{
if (Input.GetKeyDown(KeyCode.Mouse0))
{
if (Inventory.instance.space <= Inventory.instance.items.Count)
return;
pickupSound.clip = item.pickupAudio[Random.Range(0, item.pickupAudio.Length)];
pickupSound.Play();
UnityEngine.Debug.Log(item.name + " Has Been Added To Inventory.");
//Add to Inv Dict
Inventory.instance.Add(item);
PickupIcon.SetActive(false);
Destroy(this.gameObject);
}
}
}
[6481015--728113--Item.cs|attachment](upload://nUZdxFVsqhC0KhgIX4jC7JGut5K.cs) (1.84 KB)
[6481015--728116--ItemScriptable.cs|attachment](upload://oopunOebmnzTv3DazkVBTt0IpyN.cs) (365 Bytes)