Hi folks, I have a problem and haven’t found a solution yet. I hope you can help me. I would like to add an item to my inventory by clicking on it in my 3D game. This should only work if the player is close to the item. This should be made possible by an OnTriggerEnter and OnTriggerExit method. The method checks whether an object that triggers with the player’s TriggerCollider has the tag “Selectable” and renames it “SelectableNP”. The OnTriggerExit method does the opposite. If I would click on the item then the selector script takes over. This checks whether the left mouse button was pressed and uses a raycast hit to determine whether I clicked on the collider of a game object with the “SelectableNP” tag. If so, it adds the GameObject to the inventory.
But the mistake comes in between: I can’t collect the item. Actually all three methods work because I have successfully tested them all. It seems to be because I can’t use both at once. At least I think so. But I’m not giving up and still hope that someone can find a solution.
Here are the OnTriggerEnter and OnTriggerExit methods:
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Selectable"))
{
other.gameObject.tag = "SelectableNP";
}
}
private void OnTriggerExit(Collider other)
{
if (other.gameObject.CompareTag("SelectableNP"))
{
other.gameObject.tag = "Selectable";
}
}
And here is the update method of the selector script:
private void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
if (hit.collider.gameObject.CompareTag("SelectableNP"))
{
IInventoryItem ItemToCollect = hit.collider.GetComponentInParent<IInventoryItem>();
inventory.AddItem(ItemToCollect);
}
}
}
}