Getting NullReferenceException when trying to use OnPointerDown to display a RawImage

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

public class PointerDown : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    //Detect current clicks on the GameObject (the one with the script attached)
    public void OnPointerDown(PointerEventData pointerEventData)
    {
        //Output the name of the GameObject that is being clicked
        Debug.Log(name + "Game Object Click in Progress");
       
        gameObject.GetComponent<RawImage>().enabled = true;
    }

    //Detect if clicks are no longer registering
    public void OnPointerUp(PointerEventData pointerEventData)
    {
        Debug.Log(name + "No longer being clicked");
    }
}

I have this added to a button and the Debug.Log works for it. It just is giving me a NullReferenceException for the RawImage that I am trying to display.

Do you have a RawImage component on the same GameObject that this script is attached to?

I think so… I dropped the RawImage onto the button that I am trying to do this with and it is a child of the button. If you think there is a different way that would be better I am open to suggestions.

There’s no need to guess. Look at the inspector of the object. Do you see both your script and the RawImage component in the list of components?

If not, this won’t work. GetComponent can only get you components on the GameObject that it is called on - in this case, the same one your script is attached to. If the RawImage is on a child of the object, you can try GetComponentInChildren. Alternatively, just create a public RawImage myImage field and you can drag the RawImage from wherever it is in your scene into the field and get rid of GetComponent entirely.

1 Like

Thank you! I didn’t realize I could make the RawImage a component of the button (it actually won’t let me because I used an Image for the button) but I am pretty sure I can get it to work knowing that now. Thank you so much!! :slight_smile:

The GetComponentInChildren works best for this case btw it seems… thank you again!