Search Unity

Place an UI Element relative to another, depending on it's size

Discussion in 'UGUI & TextMesh Pro' started by GesunderApfel, Jan 14, 2021.

  1. GesunderApfel

    GesunderApfel

    Joined:
    Apr 4, 2015
    Posts:
    8
    Hey guys,

    I can't find the solution to a simple problem (at least in my eyes it should be one).

    I just want to place an image (ui cursor) to an ui element (a text), whilst the offset remains the same even after the screen size changes (NOT the resolution, thou, that would be nice too).

    The Canvas is set to Overlay and Scaler "Scale with Screen Size" and the ui element is part of a grid layout (if it matters). Setting the image directly on the ui element is no problem.

    Code (CSharp):
    1. var uiElementRectTransform = uiElement.GetComponent<RectTransform>();
    2. var newPosition = uiElementRectTransform.position;
    3. image.rect.position = position;
    Now, i dont want the cursor to be set in the center of the text, but to the left side of it. I figured to try something like this:

    Code (CSharp):
    1. var uiElementRectTransform = uiElement.GetComponent<RectTransform>();
    2. var newPosition = uiElementRectTransform.position - Vector3.right * (uiElement.rect.width * 0.5f);
    3. image.rect.position = position;
    But this doesn't work at all. I have to play with magic numbers which are not just bad but also useless because after changing the size of the Game Window the cursor is in the wrong position. I played around with some RectTransformUtility-methods and anchoredPosition, but I can't get it working ^^" Any ideas?