unity-game-engineuser-interface

Affecting ContentSizeFitter when resizing child object


I have a container object with LayoutElement (min height 200), ContentSizeFitter(Unconstrained, Preferred Size) and a vertical layout group.

ObjectB needs to have its height animated to shrink and the container object should rescale accordingly (disappearance effect). When changing the value in editor mode and dragging, it shows fine but once running, the values change but not the visual.

        timer = 0f;
        rt = _buttonReceivedContainer.GetComponent<RectTransform>();
        startPos = rt.sizeDelta.y;
        while (timer < 1)
        {
            float lerp = Mathf.Lerp(startPos, 0, timer);
            rt.sizeDelta = new Vector2(rt.sizeDelta.x, lerp);
            timer += Time.deltaTime * speed;
            Canvas.ForceUpdateCanvases();
            yield return null;
        }

I tried with WaitForEndOfFrame or LayoutRebuilder.ForceRebuildLayoutImmediate(rt) and the result is always same, no resizing of the container and it keeps its original size while ObjectB resizes properly.


Solution

  • It could be that ContentSizeFitter is set in OnEnable, probably to save on performances. So my solution would be to disable/enable to force a redraw.

    I cannot tell if that's the best and only solution, but it works.

        ContentSizeFitter csf = GetComponent<ContentSizeFitter>();
        while (timer < 1)
        {
            // Lerp code
            csf.enabled = false;
            csf.enabled = true;
            yield return null;
        }