Search Unity

  1. Unity 2019.1 beta is now available.
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. We're looking for insight from anyone who has experience with game testing to help us better Unity. Take our survey here. If chosen to participate you'll be entered into a sweepstake to win an Amazon gift card.
    Dismiss Notice
  4. Want to provide direct feedback to the Unity team? Join the Unity Advisory Panel.
    Dismiss Notice
  5. Unity 2018.3 is now released.
    Dismiss Notice
  6. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice

Unity UI [Solution] LayoutElement fit parent with aspect ratio

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

  1. Vapid-Linus

    Vapid-Linus

    Joined:
    Aug 6, 2013
    Posts:
    49
    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.
     
  2. Iq110

    Iq110

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

    Attached Files: