I have a UI canvas (outer black box) which has a panel (inner black box) which contains a GridLayoutGroup component, which in turn dictates the position of the inner 3 boxes. What I need is, on an event, to animate any one of the inner boxes to expand in size to fill the screen.
Since, the 3 small inner boxes position’s are controlled by the GridLayoutGroup, animating the objects directly doesn’t work as required. So my idea was to duplicate the smaller box, make it’s parent the canvas, but keep it’s position and size, and then animate the duplicate as required (so the fact that this is even a duplicate is unbeknownst to the user).
I’m not sure how to retrieve a given UI element’s position with respect to another anchor point (i.e. that of the grandparent, the canvas) so that the duplicated box is instantiated in the same position and can then be animated. Any ideas? Perhaps there is a better way of achieving this?
Apologies in advance if this is basic, this is my first Unity project!
You just need to walk the .parent tree (gameObject.parent) for the game object you are basing this on. Once you have the parent, get it’s RectTransform component and then use the anchoredPosition and parent values.
Duplicating the item and working with the duplicate is probably the right option, as un-parenting and re-parenting a child can cause all sorts of mess.
Thank you very much for your reply. Apologies for not thanking you sooner, all of a sudden work became manic and I had to put all personal projects aside until recently and I’ve only just remembered this sticking point!
I have 3 components involved:
button (the button which is to be cloned)
canvas (the main canvas)
buttonClone (the clone of button, which I need to set to be in exactly the same size and position as button, but with it’s parent as the canvas)
I now understand how to get the canvas object using .parent (thanks!):
Where i’m stuck is getting button’s anchored position with respect to the canvas object (it’s great great grandparent). If I use .anchoredPosition on either “button.transform.GetComponent().anchoredPosition” or “canvasObj.transform.GetComponent().anchoredPosition” it gives back the position relative to it’s anchor point. I really need the button anchored position “with respect to the canvas” if that makes sense? Then I need to set the anchoredPosition on buttonClone to be the resulting Vector2… and this should (in my mind at least) effectively create a clone, with parent as canvas, in exactly the same size and position as button it is a clone of.
I would take a different approach. I’d use intermediate panels between my layoutgroup and the buttons. That way you could reparent the button without any issues.