- Home /
Tweening a RectTransform between AutoLayouts?
I have two HorizontalLayoutGroups, each with some unknown number of items in them. I want to move an object from one to the other. This seems simple enough:
theObject.transform.SetParent(otherLayoutGroup);
// Wait one frame for the other layout group to update it's position
However, what I actually want is to do a nice tween to animate the object moving from its current position on screen to the new position. I can't figure out a good way to do this. As far as I can tell, there is no way for me to figure out what an object's position in the new layout group would be without actually moving it there and waiting for the layout group to update.
// Save the object's old position
previousPosition = theObject.GetScreenPosition();
// Calculate the destination position
theObject.transform.SetParent(otherLayoutGroup);
// Wait a frame
var newPosition = theObject.GetScreenPosition();
// Move the object to a non-auto-layout layer so nothing
// screws with its position while I'm trying to tween it.
theObject.SetParent(someOverlayLayer);
// Do the tween
theObject.setScreenPosition(previousPosition);
theObject.TweenPosition(newPosition);
// Wait for the tween to finish
// Add the object to the destination layout group for real this time
theObject.SetParent(otherLayoutGroup);
There are a still some problems with this approach though. First of all, GetScreenPosition() and SetScreenPosition() don't exist and I'm not entirely sure how I'd implement those. Presumably I'd do so by reading/modifying the object's transform.position, but I'm not sure how that relates to the offsets that I'm used to dealing with for RectTransforms.
Even then, this solution isn't great. First of all, I have to wait a frame for the destination layout group to update before I can start tweening, so the object will appear to warp to its destination for a frame before it begins moving. Also, I can't have the object parented to either of the layouts while it's in transit, meaning that any other objects in either layout group will immediately "snap" as soon as the tween begins or ends and I call SetParent.
Moving an object from one layout group to another seems like a common enough task that there must be a better way to do this that I just haven't figured out yet. Does anybody have any suggestions? Thanks for any help!