I have an IEnumerator coroutine in which I call the UIManager script to update the Image size to fit the text size but it doesn't happen. when I use yield return new WaitForEndOfFrame() it sometimes solve the problem. but I don't want to use it.

edit: I tested the code like I was suggested in an empty unity project and it still happens, the width should change according to the text size but it happens opposite (when the text is small the width of the image is large and when the text is large the width of the image is small) (it only happens correctly at the first time - the width of the image fits the text width)

public class Example : MonoBehaviour
    public Image image;
    public Text text;
    private int k = 0;

    public void ButtonClick()
        text.text = (k % 2 == 0) ? "10" : "10 / 10";
        image.rectTransform.sizeDelta = new Vector2(text.rectTransform.rect.width, 30);

edit: Solved! thanks for the help, Canvas.ForceUpdateCanvases() did the trick

  • \$\begingroup\$ You have typos in UIManager.instace.DisplayPlayerScore(); and UIManager.instace.UpdatePlayerScore(CalcaulatePlayerScore(playerHand));--> should be instance. You should use IDE that will make you aware of typos. \$\endgroup\$ – codeepic Feb 4 at 13:11
  • \$\begingroup\$ @codeepic thanks I've changed it in the IDE, but that's not the problem, it was called 'instace' originally also. \$\endgroup\$ – mountSin Feb 4 at 13:24
  • \$\begingroup\$ @DMGregory I did what you suggested and I made the problem in a new unity project and it still happens \$\endgroup\$ – mountSin Feb 4 at 14:39
  • \$\begingroup\$ Thanks! Now it's much clearer what's going on. Looks like the UI system hasn't done its re-layout pass yet to update the size of the rectTransform based on the new text string, so you're still working from the old width when that next line runs. There may be a method you can call to force a layout update immediately, or there may be a post-layout event that you can hook into. \$\endgroup\$ – DMGregory Feb 4 at 14:45
  • \$\begingroup\$ Please post an Answer to explain your solution. Our system doesn't know to recognize "edit: Solved!" as an answer, so it will continue to consider this question unanswered until an Answer is posted below. \$\endgroup\$ – DMGregory Feb 4 at 23:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.