0

I'm a little new to unity and I'm unsure how to do this:

I've added a panel control to my app. I want to call a function on a script when the user touches the panel, and I want to receive the location of the touch in panel coordinates. None of the components seem to be able to do this. Maybe I have to write a bunch of raw code to watch all touches, do collision checks, etc?

Eric Jorgensen
  • 1,682
  • 2
  • 14
  • 23

1 Answers1

0

The solution is to use Raycasting:

public static bool Raycast(Ray ray, out RaycastHit hitInfo, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);

using UnityEngine;

public class ExampleClass : MonoBehaviour
{
    void Update()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        if (Physics.Raycast(ray, out hit, 100))
            print("Hit something!");
    }
}

The example tells you how, you only need to know if the thing you touched was your panel.

For this, you need to use RaycastHit, checking the transform's names can be a good way.

z3nth10n
  • 2,341
  • 2
  • 25
  • 49
  • "to call a function on a script when the user touches the panel" Panel sounds like a UI component to me and not an object with a collider. Raycast is not used for that. – Programmer May 10 '18 at 01:02
  • Well, this is a valid solution for a Gameobject panel, it can helps someone. – z3nth10n May 10 '18 at 01:05
  • rather than doing raycast on your own, (for most frames for most objects it will fail) its best to let unity's Event System do the job. if you implement IPointerClickHandler interface you will get a callback with PointerEventData parameter which will contain the coortinates, its much faster and less error prone to just use an existing solution – zambari May 10 '18 at 08:16