Can't find true position for UI element

In my UI, I have a “container” section with a horizontal layout group, and my script fills this at run time with prefabs of some UI elements. The horizontal layout group automatically lines everything up and spaces them out, so it looks right no matter how many prefabs I spawn into the group.
Everything to this point is working right.

for (int x = 0; x < GameManager.RM.FindNumberOfStagesForThisWorld(HighlightedWorld); x++)
        {
            StageBlocks[x] = Instantiate(StagePrefab, StageContainer.transform);
            StageHelper Helpr = StageBlocks[x].GetComponent<StageHelper>();

            // followed by a bunch of code to set up the visual style of these elements
  
        }

But I’ve also got a little cursor that moves around to these prefabs. I was simply going to move the position of this element to match the position of the prefab, like so.

StageCursor.transform.position = StageBlocks[HighlightedStage - 1].transform.position;

But the problem is that this position isn’t in the correct place. It’s plopping it out into the corner of the container.
The best I can figure is that it is reading the transform position of where the prefab was spawned, not where it is being displayed as being, since the horizontal layout group is adjusting its position.
If there’s something else that could be causing this, I’d be interested in knowing, but I can’t quite fathom what.

  • Make sure that your cursor object is not a child of the object with a layout group.
  • Your cursor is also a UI element.

If you want to keep the cursor in the current hierarchy but don’t want it to be impacted by the layout group, add Layout Element component to it and check the Ignore Layout

9546007--1348582--upload_2023-12-24_9-27-37.png

1 Like

It isn’t; I have a function that completely clears the content of the layout group before repopulating it with new objects, so I can’t keep my cursor within that layout group.

I have other UI elements that I move around without any problem. I recall having problems when I tried to feed the RectTransform a vector2 numerical value, so I just added dummy objects into my UI and had the, move to the same position. This worked.
But it isn’t working with the layout group objects.

I guess I could give that a try, but it would require me to completely overhaul the whole system. It’s a lot of effort for something that might not even work…

Could be a timing issue. When are you updating the cursor position?
Try doing it in LateUpate() or a WaitForEndOfFrame coroutine or even 1 or 2 frames after enabling the layout group.
Interesting thread related to this: https://discussions.unity.com/t/608126 page-2

Iirc correctly I once had a case where I had to wait two full frames before the layoutgroup had settled into the final position.