I know there are answers and threads about this already, most of them only have incomplete information and none mention all the things that can go wrong or explain what is going on in the background.
I am a professional UI builder in my day job, and although having a graphical editor for UIs can be useful, not being able to access and change any and all UI content from code at runtime is totally unacceptable.
I started building my own UI element prefabs in the hope of generating a modest library I could use across my projects, that allows simple UI elements to be added and positioned in the UI as required at runtime.
When accessing a RectTransform I can change its width, height, sizeDelta, anchorMin and -Max, localPosition, localScale, parenting and offsetMin and -Max and pivot. Seems great at first.
But when changing these values I noticed that the values that the transform had after the changes were not the same as the ones I input. Sometimes orders of magnitude different. It is clear that there is a calculation being done in a subsequent frame that recalculates all values based on the input values. I understand why this is the case, the transform needs to be dynamic based on resolution and aspect ratio, and I wish to take advantage of that feature and not switch it off. But this process is totally opaque, and as far as I can tell, not controllable.
It also appeared that the order in which the values were changed produced a different result. After trying countless different orders, and hours of frustrating trial and error, the only real step forward I have achieved is to understand that touching the pivot values in anyway is a big mistake and teleports the transform thousands of units into the middle of nowhere every time.
Is anyone able to shed some light on this situation? To narrow down the scope of answers I would love a description of how to achieve the following:
Given a canvas that fills the screen area, I would like to create a simple context menu. The steps would be
- Created menu object in code
- Load a prefab and parent it to the UI canvas
- Position the menu transform/canvas in the correct position on the screen
- Size the width of the element based on the widest content element
- Size the height of the element based on the number of content elements
- Generate all the content elements
- Place them inside the menu element
What I am asking for here is instructions on how to achieve steps 3 to 5. Descriptions of why and how something works are also appreciated.
I doubt I am the only one who would like context menus in their game so this should hopefully be of general use to the community.
Thanks in advance