Posts Tagged Screen

NGUI Unity3d : Getting Screen size

I have been doing some Unity recently and so far it has been going very well. Hum, I bang my head on the wall sometimes but overall it’s fun. Except for when you search for something trivial and you can’t find anything. You see, they can say what they want but Unity isn’t a mature tech yet.

I am mostly doing UI, so I am using NGUI. It’s pretty neat, does pretty much what I want, but sometimes it doesn’t expose what I need, like the size of the screen. Well Unity has the Screen class where you can get the width and height of the screen and that is what I was using until I ran into some problems. I started by testing on my Nexus 4, then on the Nexus 7 and everything was fine until I tested on the Nexus 10. You see the Nexus 10 has a huge resolution and it was bigger than a little value that I hadn’t figured out what it was doing yet. The maximum height value on the UIRoot Script. This is actually a pretty nifty little thing. You see NGUI does some magic in the back when the resolution of the device exceed this value. It will scale the size of a pixel to be bigger that 1×1, scaling your content at the same time. When this happens the values of Screen.width and Screen.height are not measured in the same pixel unit has the NGUI one. So if you scale some background according to the number of pixels of your screen, it will be scaled way too big.


So I made this little static class to get myself the screen size in NGUI’s unit. I basically get the activeHeight from the UIRoot and I derive the NGUI Screen height and width from it. Here is the code:

public class DisplaySize{
	protected static DisplaySize _instance;
	public static DisplaySize instance{
		get {
			if (_instance == null){
				_instance = new DisplaySize();
			return _instance;
	public GameObject gameObject;
	public float width;
	public float height;
	public void CalculateSize(){
		UIRoot mRoot = NGUITools.FindInParents<UIRoot>(gameObject);
		float ratio = (float)mRoot.activeHeight / Screen.height;
		width = Mathf.Ceil(Screen.width * ratio);
		height = Mathf.Ceil(Screen.height * ratio);

So somewhere in your initializing code you need to pass it a gameObject that is a children of UIRoot and call CalculateSize. After that you can call DisplaySize.instance.width from anywhere in the code.

I am pretty new to Unity, so if you got a better way to do this, leave it in the comments.

, ,

No Comments

Parse error: syntax error, unexpected ';' in /homepages/25/d169645162/htdocs/wp-content/themes/fusion/footer.php on line 13