Wednesday, January 29, 2014

Unity GUI Tutorial - Scale GUI to the right size for every resolution


Check out the code below the videos
GUITextures




This Unity Tutorial will show you how to make your GUI automatically scale to the right size for every screen resolution and aspect ratio.

Twitter: https://twitter.com/Devination3D

To connect your device to unity, download the unity remote app and follow these steps: http://answers.unity3d.com/questions/198853/unity-remote-for-android-not-working-solution.html

Time Breakdown:
1:20 - Overview of different aspect ratios for mobile and desktop
2:00 - Demonstration and explaination of why Pixel Inset values are not good for scalability
3:10 - Explaination of how Pixel Inset values work
5:00 - Use Transform Position and Scale values instead!
7:30 - GUITexture anchor points are in the center by default
7:50 - How to change the anchor point of a GUITexture (useful for health bars and such)
9:45 - Demonstration of why you can't get perfect squares and circles without code
10:10 - Using a script to make a perfect square GUITexture
11:39 - Explaination of how the script works
15:20 - Outro Thanks for watching :D


GUIText
Check out the videos above to hear the explanation and see the code in action
/*/
* Script by Devin Curry
* www.Devination.com
* www.youtube.com/user/curryboy001
* Please like and subscribe if you found my tutorials helpful :D
* Twitter: https://twitter.com/Devination3D
*
* Attach this script to a GUITexture or GUIText to fix its scale to the aspect ratio of the current screen
* Change the values of scaleOnRatio1 (units are in % of screenspace if the screen were square, 0f = 0%, 1f = 100%) to change the desired ratio of the GUI
* The ratio is width-based so scaleOnRatio1.x will stay the same, scaleOnRatio1.y will based on the screen ratio
*
* The most common aspect ratio for COMPUTERS is 16:9 followed by 16:10
* Possible aspect ratios for MOBILE are:
* 4:3
* 3:2
* 16:10
* 5:3
* 16:9
/*/
using UnityEngine;
using System.Collections;

public class GUIAspectRatioScale : MonoBehaviour 
{
 public Vector2 scaleOnRatio1 = new Vector2(0.1f, 0.1f);
 private Transform myTrans;
 private float widthHeightRatio;

 void Start () 
 {
  myTrans = transform;
  SetScale();
 }
 //call on an event that tells if the aspect ratio changed
 void SetScale()
 {
  //find the aspect ratio
  widthHeightRatio = (float)Screen.width/Screen.height;
  
  //Apply the scale. We only calculate y since our aspect ratio is x (width) authoritative: width/height (x/y)
  myTrans.localScale = new Vector3 (scaleOnRatio1.x, widthHeightRatio * scaleOnRatio1.y, 1);
 }
}