1
\$\begingroup\$

I've been recently working on a videogame, and I'm trying to make a script that will destroy the game object it is applied to whenever the right mouse button is clicked on it. It doesn't function at all and I don't receive any error messages in the Console. Here is all my code:

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class RightClick: MonoBehaviour, IPointerClickHandler
{
    // Initiates whenever the pointer is clicked
    public void OnPointerClick(PointerEventData eventData)
    {
        // Destroys item from players inventory when pressed
        if (eventData.pointerId == -2)
        {
            // Removes object from inventory
            Object.Destroy(this.gameObject);
        }
    }
}

I have searched for hours on this topic and have only found extremely outdated sources, please help me!

\$\endgroup\$
6
  • 1
    \$\begingroup\$ Walk us through how you've set up your scene. Do you have an EventSystem component present? How is it configured? What game object is this script on, and how are its other components configured? \$\endgroup\$
    – DMGregory
    Dec 31, 2020 at 4:16
  • \$\begingroup\$ @DMGregory I don’t have an EventSystem component present. This script is on a UI image that is automatically placed in the Inventory slot image whenever it’s sprite counterpart is collided with in the World Space. \$\endgroup\$ Jan 1, 2021 at 23:38
  • \$\begingroup\$ You need an EventSystem component in your scene for anything from the UnityEngine.EventSystems namespace to work. \$\endgroup\$
    – DMGregory
    Jan 1, 2021 at 23:40
  • \$\begingroup\$ @DMGregory I added the event system, but it still doesn’t work. Do you think I should restart the tutorial I was following (it’s a two part series, here are the links: youtu.be/DLAIYSMYy2g and youtu.be/OG7vHstkZqM) or do you think I should keep trying to fix my current code? \$\endgroup\$ Jan 3, 2021 at 4:23
  • \$\begingroup\$ You do not need my permission to attempt either strategy. \$\endgroup\$
    – DMGregory
    Jan 3, 2021 at 12:50

1 Answer 1

1
\$\begingroup\$

Add this script to your button.

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Events;

public class UIClickHandler : MonoBehaviour, IPointerClickHandler
{
public UnityEvent onLeftClick;
public UnityEvent onRightClick;
public UnityEvent onMiddleClick;

public void OnPointerClick(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Left)
{
onLeftClick.Invoke();
}
else if (eventData.button == PointerEventData.InputButton.Right)
{
onRightClick.Invoke();
}
else if (eventData.button == PointerEventData.InputButton.Middle)
{
onMiddleClick.Invoke();
}
}
}

I steal it from here.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .