RectTransformUtility.PixelAdjustRect returns 0 width?

I’m trying to get the width of a UI element, but PixelAdjustRect is giving me 0.

I’m using the below script that’s on a Canvas object. The passed in panel arg is a panel that already exists. I’m trying to instantiate a new panel from a prefab, and get the new panel’s width. But I’m getting a width of 0 (the panel does not have a 0 width, I can see it get instantiated and placed onto the canvas). If I instead get the width of the pre-existing, passed in panel, that gives my a non-zero value as expected.

Do I have to do something else to tell Unity to recompute the new panel’s bounds before using PixelAdjustRect?

void foo(GameObject panel)
{
    GameObject myPanel = Instantiate(myPanelFab);
    myPanel.transform.SetParent(panel.transform.parent);
    myPanel.transform.SetAsLastSibling();

    RectTransform rect = myPanel.gameObject.GetComponent<RectTransform>();
    rect.ForceUpdateRectTransforms();
    Canvas.ForceUpdateCanvases();
    float rectWidth = RectTransformUtility.PixelAdjustRect(rect, gameObject.GetComponent<Canvas>()).width;
    Debug.Log("rectWidth: " + rectWidth);
}

Look into calling LayoutRebuilder.ForceRebuildLayoutImmediate(myPanel) , just as the name suggests it recomputes the layout so it should get you there