0
\$\begingroup\$

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.

\$\endgroup\$
  • \$\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 Mar 28 '18 at 20:58
  • \$\begingroup\$ Possibly, but Patrick's answer generates the same error. \$\endgroup\$ – Kaya Suleyman Mar 28 '18 at 21:02
0
\$\begingroup\$

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

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

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

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.