Search Unity

Unity UI [Solution] LayoutElement fit parent with aspect ratio

Discussion in 'UGUI & TextMesh Pro' started by Vapid-Linus, Jul 25, 2018.

  1. Vapid-Linus

    Vapid-Linus

    Joined:
    Aug 6, 2013
    Posts:
    64
    I was struggling with the AspectRatioFitter component, as it is not allowed to be used on an object whose parent has a layout group component. I wanted to use the AspectRatioFitter in the "Fit To Parent" mode. I couldn't find any solutions so I made my own and thought to share it in case someone else has similar issues.

    Here is the script:
    https://gist.github.com/VapidLinus/d6d5f7cd62e5a8b961b63a3c46dff443

    How to use:
    1. Add a LayoutElement to your gameobject
    2. Add the LayoutElementFitParent component to the same gameobject
    3. Set the "Aspect Ratio" field value
    4. Enable either "Update Min" or "Update Preferred" (or both)
    5. The component will now update the layout element's min size and/or preffered size to make it fit in the parent
    Example:
    Here is what it should look like. Notice that "Preferred Width" and "Preferred Height" on the LayoutElement was automatically turned on and set because "Update Preferred" was checked on the LayoutElementFitParent component.


    Disclaimer:
    I haven't done extensive testing, it will probably break in some corner case scenarios. Feel free to comment with improvements/fixes if you notice any issues.
    If you turn off either updateMin or updatePreferred, you will have to manually uncheck min size or preferred size in the layout element component.
     
    gillemp and Can-Baycay like this.
  2. Bizquit110

    Bizquit110

    Joined:
    Nov 15, 2016
    Posts:
    12
    You saved my life! I'm making sudoku game and need exactly this script! Thanks!
     

    Attached Files:

  3. Can-Baycay

    Can-Baycay

    Joined:
    Dec 14, 2010
    Posts:
    27
    This really helped a lot. Thanks.

    In our case, we've spent a not-so-little time figuring out that setting up Child Force Expand and Control Child Size correctly in parent layout is crucial for LayoutElementFitParent to work.