Always pickup closest item?
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")
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<BoxCollider>();
pickupSound = GameObject.Find("Player/PickupSound").GetComponent<AudioSource>();
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);
}
}
}
Your answer
Follow this Question
Related Questions
Using downloaded image as UI Image's source image? 1 Answer
Unity 5.3 UI Button wont set Select state via script after the parent has been set inactive 0 Answers
Is there a way I can make one script for all my buttons in my game? 1 Answer
Pause menu done exactly according to tutorial doesen't work 2 Answers
Best way to simplify this code 1 Answer