Here is my Graphics RayCast code:

void Update()


if (Input.GetMouseButtonDown(0)) { 

     PointerEventData cursor = new PointerEventData(EventSystem.current); 
     cursor.position = Input.mousePosition;
     List<RaycastResult> objectsHit = new List<RaycastResult>();
     EventSystem.current.RaycastAll(cursor, objectsHit);
     Debug.Log(cursor.pointerPressRaycast.gameObject.name); //line 28

My Canvas settings has the "Graphics Raycaster" script enabled and all buttons are "RayCast target" enabled. The Canvas is of the "UI" layer, ignore reversed graphics is OFF and there are no blocking objects or blocking masks.

I receive the following error on runtime when selecting ANY canvas components:

NullReferenceException: Object reference not set to an instance of an object CivilianUnitPlacement.Update () (at Assets/CivilianUnitPlacement.cs:28)

I'm unsure why this error is being generated. Looks like the RayCaster is registering a hit, so it baffles me that it cannot return the GameObject name at line 28.

  • \$\begingroup\$ Would not RayCastAll return a boolean in the event that the list is hit? You don't seem to be testing for the case where you do not get a hit. \$\endgroup\$
    – ErnieDingo
    Commented Mar 28, 2018 at 20:58
  • \$\begingroup\$ Possibly, but Patrick's answer generates the same error. \$\endgroup\$ Commented Mar 28, 2018 at 21:02

2 Answers 2


I'm not sure if you'd want to use RayCastAll. Here's what should work:

    if (Input.GetMouseButtonDown(0))
        //Set up the new Pointer Event
        m_PointerEventData = new PointerEventData(m_EventSystem);
        //Set the Pointer Event Position to that of the mouse position
        m_PointerEventData.position = Input.mousePosition;

        //Create a list of Raycast Results
        List<RaycastResult> results = new List<RaycastResult>();

        //Raycast using the Graphics Raycaster and mouse click position
        m_Raycaster.Raycast(m_PointerEventData, results);

        //For every result returned, output the name of the GameObject on the Canvas hit by the Ray
        foreach (RaycastResult result in results)
            Debug.Log("Hit " + result.gameObject.name);

Here's the source: https://docs.unity3d.com/ScriptReference/UI.GraphicRaycaster.Raycast.html

  • \$\begingroup\$ Hi Patrick. I get the same error - object not set to an instance of an object: m_Raycaster.Raycast(m_PointerEventData, results); \$\endgroup\$ Commented Mar 28, 2018 at 21:02

Resolved - invariably, any code relating to Graphics RayCaster should be attached to the Canvas object. Problem solved.

  • \$\begingroup\$ got it, after 2 hours of code shuffling.. and for clarity, you need to add a 'GraphicsRaycaster' component to the gameObject containing the raycasting script. \$\endgroup\$
    – MSM
    Commented Oct 10, 2019 at 16:36

You must log in to answer this question.

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