0

I have 4 rectangles of identical size (each in every quadrant of screen). I created them programatically in onStart() method:

Vector3 pos1 = new Vector3(Screen.width / 4, Screen.height / 4, 0);
Vector2 rectDimensions = new Vector2(Screen.width / 2, Screen.height / 2);

GameObject bottomLeftGO = new GameObject();
bottomLeftGO.transform.SetParent(mainCanvas.transform);

Image bottomLeftRect = bottomLeftGO.AddComponent<Image>();
bottomLeftRect.color = new Color(0.192F, 0.051F, 0.125F);
bottomLeftRect.rectTransform.sizeDelta = rectDimensions;
bottomLeftGO.transform.position = pos1;

Currently, screen looks like this: RectangleScene

mainCanvas is a prefab I created in Unity GUI, and connected it to the script in which I made rectangles.

I want to detect touches on the rectangles in Update() method. I tried using Raycast like this:

if (Input.touchCount > 0)
{
    foreach (Touch touch in Input.touches)
    {
        Ray ray = Camera.main.ScreenPointToRay(touch.position);

        if (Physics.Raycast(ray, out hit, touchInputMask))
        {
            GameObject hittedObject = hit.transform.gameObject;
        }
    }
}

But the condition if (Physics.Raycast(ray, out hit)) always returns false. I tried it using Input.GetMouseButton(0) so I do not need to build .apk on phone, but it still fails to detect any hits.

I am fresh new to Unity and do not understand all the concepts, so If anyone has an idea what could I try or has the solution I would be more than glad to listen. Thank you.

spamserv
  • 165
  • 3
  • 15
  • 1
    Change Image to Button :D. AND ................ wait for it ......... legendary ... – Cổ Chí Tâm Mar 10 '17 at 09:25
  • You really don't have to use a `Button` here if it doesn't need `Text` and all those transition stuff. If you simply want to detect click on an image then `Image` component is fine. You don't raycast UI elements with `Physics.Raycast`. How to do this is provided in the first part of answer in the duplicated question. – Programmer Mar 10 '17 at 09:33
  • @Programmer How do I attach that "ClickDetector" script to a programatically created object? Do I even have to do it or it's an event handler for all clicks/touches? – spamserv Mar 10 '17 at 09:40
  • 1
    Never mind, I understood everything. Thank you. – spamserv Mar 10 '17 at 09:44
  • You are welcome! – Programmer Mar 10 '17 at 09:51

0 Answers0