Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Getting GameObject of clicked UI Image

Discussion in 'Immediate Mode GUI (IMGUI)' started by Mir0da, Jun 20, 2023.

  1. Mir0da

    Mir0da

    Joined:
    Apr 21, 2023
    Posts:
    1
    Hey Guys,

    i'm trying to get the GameObject info of an Image that is clicked in UI.
    i tried do use Raycast2D but i didn't get any information.
    i cant use a Button because the rest of my program looks if i hit the Objects in the right order, so i need a GameObject that can be compared with my stored GameObjects.

    This is my Code.
    The 3D version that i use when running around in the 3D world works like a charm.
    But i cant get any Information about hitting an image on the UI when i open my inventory.

    Code (CSharp):
    1. if (InventoryController.isClosed == true)
    2.         {
    3.             if (Input.GetMouseButtonDown(0))
    4.             {
    5.                 Ray ray = cam.ScreenPointToRay(Input.mousePosition);
    6.                 RaycastHit hit;
    7.  
    8.                 if (Physics.Raycast(ray, out hit, 20.0f, layerMask))
    9.                 {
    10.                     CheckInteractionOrder(hit.transform.gameObject);
    11.                 }
    12.             }
    13.         }
    14.         else
    15.         {
    16.             if (Input.GetMouseButtonDown(0))
    17.             {
    18.                 Vector2 worldPoint = cam.ScreenToWorldPoint( Input.mousePosition );
    19.                 RaycastHit2D hit = Physics2D.Raycast( worldPoint, Vector2.zero );
    20.  
    21.                 if (hit.collider != null)
    22.                 {
    23.                     CheckInteractionOrder(hit.transform.gameObject);
    24.                     Debug.Log(hit.transform.gameObject.name);
    25.                 }
    26.             }
    27.         }
    Thanks for all answers!

    EDIT: The picture has a Box Collider 2D and is a Raycast Target