After some Youtube tutorials by Sykoo, along with some of my own tweaks, I have an inventory system and items you can pick up by right clicking on them.
In fact, there’s already a system for detecting if the player is within reach of the item.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Item : MonoBehaviour
{
public int ID;
public string type;
public string description;
public Sprite icon;
[HideInInspector]
public bool equipped;
[HideInInspector]
public GameObject weapon;
[HideInInspector]
public GameObject weaponManager;
public bool playersWeapon;
public Inventory inventory;
public GameObject player;
public bool withinReach;
public void Start()
{
inventory = GameObject.Find("Player").GetComponent<Inventory>();
player = GameObject.Find("Player");
weaponManager = GameObject.FindWithTag("WeaponManager");
if(!playersWeapon)
{
int allWeapons = weaponManager.transform.childCount;
for (int i = 0; i < allWeapons; i++)
{
if(weaponManager.transform.GetChild(i).gameObject.GetComponent<Item>().ID == ID)
{
weapon = weaponManager.transform.GetChild(i).gameObject;
}
}
}
}
private void OnTriggerEnter(Collider player)
{
withinReach = true;
}
private void OnTriggerExit(Collider player)
{
withinReach = false;
}
public void OnMouseOver()
{
if (withinReach && Input.GetMouseButtonDown(1))
{
inventory.AddItem(this.gameObject, ID, type, description, icon);
}
}
public void Update()
{
if (equipped)
{
if (Input.GetKeyDown(KeyCode.G))
{
equipped = false;
this.gameObject.SetActive(false);
}
}
}
public void ItemUsage()
{
//weapon
if(type == "Weapon")
{
weapon.SetActive(true);
weapon.GetComponent<Item>().equipped = true;
}
//health item
//beverage
}
}
The problem is that I have a normal box collider for actually clicking on the item, and a sphere collider set as a trigger to detect if the player is within reach of the item.
But it simply uses the sphere collider for everything and ignores the box collider. When I shoot near the item, the debugger tells me I’m hitting the item because the ray is hitting the sphere collider. And it can also make it tricky to actually pick up the item by clicking on it.
If I move the sphere collider further down the list in the inspector, it just moves it back up when I start the game.
Is there any way I can remove the sphere collider and use Physics.OverlapSphere instead? Or something like that?