作为Unity3d的初学者,遇到了许多的问题,相信很多的人都遇到了屏幕自适应的问题,现在网上的NGUI自适应说的很多,大多都是些复制粘贴的水贴。借着国庆,研究了两天,把经验分享给大家,希望对大家有用,本人用的NGUI版本是3.6.7 Unity使用的是4.3.4f1.
第一步: 创建自己的UI
在Hierarchy试图中可以看到
第二步: 在Camera下面创建(create)Anchor
第三步:在Anchor下面创建你自己的Panel -》 方法如同第二步
如上图,我需要创建5个Panel,分别是:中上,右上,中右,右下,左下。
第四步:
(1)分别在UI上添加缩放脚本StrechUI(可自定义);
(2)Camera,Anchor,各个Panel上添加NGUI自带的UIAnchor;
(3)在各自的Panel的UIAnchor上的Side选择不同的对其方式;(按照第三步的说明:中上,右上,中右,右下,左下)
(4)在不同的Panel中添加所需的子控件(如:Label,Button,ProgressBar,Texture等)
(5)在Unity的Scene窗口中,手动的调节各个子控件的位置,(注意:子控件的位置是相对于其对应的Panel的位置) -》 调整位置的时候,注意其Panel的对齐方式,如:右上角的控件,需要放在RightTopPanel原点的左下才能被Camera投影到;
第五步:
在UI上添加的缩放脚本,可以根据自己的需求去编写,贴上本文的StrechUI:
using UnityEngine;
using System.Collections;
public class StrechUI : MonoBehaviour
{
public UIPanel CenterTopPanel;
public UIPanel RightTopPanel;
public UIPanel RightPanel;
public UIPanel RightBottomPanel;
public UIPanel LeftBottomPanel;
void Awake()
{
float scale = 1;
if (Screen.height * 1280.0f / Screen.width / 720.0f > 1)
{
scale = Screen.height / 720.0f;
}
else
{
scale = Screen.width / 1280.0f;
}
CenterTopPanel.transform.localScale = new Vector3(Screen.width / 1280.0f, Screen.height / 720.0f, scale);
RightTopPanel.transform.localScale = new Vector3(Screen.width / 1280.0f, Screen.height / 720.0f, scale);
RightPanel.transform.localScale = new Vector3(Screen.width / 1280.0f, Screen.height / 720.0f, scale);
RightBottomPanel.transform.localScale = new Vector3(Screen.width / 1280.0f, Screen.height / 720.0f, scale);
LeftBottomPanel.transform.localScale = new Vector3(Screen.width / 1280.0f, Screen.height / 720.0f, scale);
}
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
}
}
代码的if语句似乎有点问题,大家就参考参考就行。 别忘记在UI的StrechUI脚本中选着Panel哦
到此为止,运行起来就OK了。
如有错误,希望大家指出来,多交流,谢谢。