Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Parent size fit child size

Discussion in 'UGUI & TextMesh Pro' started by GGEEK, Jul 28, 2015.

  1. GGEEK

    GGEEK

    Joined:
    Jul 1, 2015
    Posts:
    12
    Now I have an Image. The image has a Text as its child. The Text has a component Content Size Fitter.
    The width of Text depends on the length of the text. What I wish is to make the width of Image depends on the width of Text. Because of the Content Size Fitter, I can't get the width of Text (It's always 0).
     
  2. wpdev

    wpdev

    Joined:
    Jan 10, 2015
    Posts:
    8
    If you make text parent of image and set image stretch width, you will have image size of text
     
  3. GGEEK

    GGEEK

    Joined:
    Jul 1, 2015
    Posts:
    12
    If I do this, the image will cover the text.
     
  4. wpdev

    wpdev

    Joined:
    Jan 10, 2015
    Posts:
    8
    My bad, tested this solution without overlaying image and text. Ok, then to get this working scripting should be used. To get actual text use
    Code (CSharp):
    1. int textWidth = text.rectTransform.rect.width;
    but keep in mind that text width don't update immediately after setting(i guess it happens in LateUpdate() ). This mean that image size could be updated on the next frame.
    Example:
    Code (CSharp):
    1.     void  MyMethod()
    2.     {
    3.         Text.text = "hello world";
    4.         StartCoroutine(ImageSizeUpdate());
    5.     }
    6.  
    7.     IEnumerator ImageSizeUpdate()
    8.     {
    9.         yield return 0;
    10.         image.rectTransform.sizeDelta = new Vector2(Text.rectTransform.rect.width, image.rectTransform.rect.height);
    11.     }