【Unity3D】【NGUI】屏幕自适应

38 篇文章 3 订阅

NGUI讨论群:333417608


注意:NGUI3.6.x版本及以上,建议使用UIStretch与UIWidget的Anchor功能。


(以下为老版本时写的)

看过一些文章,大多数都用UIStretch。说实话我并不喜欢用这个脚本。

我一直对那些在屏幕适应上出现问题的人推荐使用UIRoot的ManualHeight。

先提供三个截图。看看效果是否是你想要的。旁边空白出来的地方,你需要和策划、美术商量用一些背景挡住。

1、正常开发分辨率下:


2、看起来较细的分辨率:


3、看起来较宽的分辨率:


使用注意:

1、和策划制定好开发时分辨率。这很重要,要保证所有UI都在同样的分辨率下制作,比如是W*H。

2、把我这个脚本挂在UIRoot上。UIRoot的Scaling Style修改为FixedSize。

3、aspectRatioHeight、aspectRatioWidth分别为开发时的高(H)和宽(W)。

4、每个UIRoot都需要调整ManualHeight到和策划制定的高度(H)。

5、Unity3D的Game窗口,调整到相应的分辨率(W*H)。


(感谢成都-大强提供以下版本。注意:UICamera.onScreenResize是3.0+版本的,如果报错请删除即可

using UnityEngine;

[ExecuteInEditMode]  
[RequireComponent(typeof(UIRoot))]
public class SZUIRootScale : MonoBehaviour
{
	public int aspectRatioHeight;
	public int aspectRatioWidth;
	public bool runOnlyOnce = false;
	private UIRoot mRoot;
	private bool mStarted = false;

	void Awake()
	{
		UICamera.onScreenResize += ScreenSizeChanged;
	}

	void OnDestroy()
	{
		UICamera.onScreenResize -= ScreenSizeChanged;
	}

	void Start()
	{
		mRoot = NGUITools.FindInParents<UIRoot>(this.gameObject);
		
		mRoot.scalingStyle = UIRoot.Scaling.FixedSize;
		
		this.Update();
		mStarted = true;
	}

	void ScreenSizeChanged()
	{ 
		if (mStarted && runOnlyOnce) {
			this.Update();
		} 
	}
	 
	void Update()
	{
		float defaultAspectRatio = aspectRatioWidth * 1f / aspectRatioHeight;
		float currentAspectRatio = Screen.width * 1f / Screen.height;

		if (defaultAspectRatio > currentAspectRatio) {
			int horizontalManualHeight = Mathf.FloorToInt(aspectRatioWidth / currentAspectRatio);
			mRoot.manualHeight = horizontalManualHeight;
		} else {
			mRoot.manualHeight = aspectRatioHeight;
		}

		if (runOnlyOnce && Application.isPlaying) {
			this.enabled = false;
		}
	}
}

评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值