Search Unity

Question Get X,Y Position Of UI element in Global Space. How?

Discussion in 'Getting Started' started by Sparticus, Sep 12, 2022.

  1. Sparticus

    Sparticus

    Joined:
    Mar 15, 2014
    Posts:
    149
    Hey all,

    I had asked this question previously but didn't get the answer. I've been stuck on this for many days now and really need help. I'm guessing my original question was not clear so I will try again to hopefully make it more clear.

    I have my Canvas (Render mode is Screen Space - Overlay) which I use to display my UI to the user. When the user clicks to view their profile, in the top left of the screen I show them a few UI elements including their username.

    upload_2022-9-12_13-50-8.png

    If I check the Hierarchy within Unity, you can see the actual "UserNameText" game object is many levels deep. This is the element where I display their username.

    upload_2022-9-12_13-51-20.png

    I am making a game tutorial where I need to dynamically point an arrow at specific elements on the UI. Since each users screen size will be slightly different with different aspect ratios, I can't hardcode the positions of the elements I want to point to with the arrow.

    I need to create a function that accepts a game object that could be many levels deep in other objects, and it returns the global screen position I can place the arrow. This position is not the x,y position of the element (ie. gameObject.transform.position) as that element is many levels deep (and it's parents are not all at 0,0). (for simplicity of this question I assume zero for all z positions).

    For example, if the parent object (which is at the root of the canvas) is at 10,10... and the child within that parent is at 5,5..... I want my function to return 15,15. So if I placed my arrow at the root of the canvas at 15,15 it would be right over that object.

    I assume there is a 1 line of code method provided by Unity to do this, but I can't seem to locate it.

    If anyone could help me out I would be forever grateful!!

    Thanks!
    Ryan
     
  2. Sparticus

    Sparticus

    Joined:
    Mar 15, 2014
    Posts:
    149
    Hmm....... apparently the answer was just :

    gameObject.transform.position
     
    Last edited: Sep 13, 2022
  3. Sparticus

    Sparticus

    Joined:
    Mar 15, 2014
    Posts:
    149
    Nevermind....it's a tad more complicated than that. That only works if your game canvas is the exact same size as the devices' resolution.

    So, you need to take into account and do some basic math to take into account their screen resolution to get the value on your canvas