生活随笔
收集整理的這篇文章主要介紹了
这里先发布一个,自己写得unityUI的适配的方案(插播)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
這個(gè)適配是依據(jù)坐標(biāo)系的象限的思想來進(jìn)項(xiàng)適配的。參考了部分的NGUI的適配方案。
在程序的事實(shí)上,來測量UI距離相機(jī)邊界的像素然后依據(jù)比例來進(jìn)行適配,個(gè)人認(rèn)為還不錯。 放碼!
。
有個(gè)前提哦就是你要先定一個(gè)尺寸。
假如我優(yōu)先適配1024*768。那在放置這個(gè)腳本之前,要把自己的界面還成1024*768的哦。我是依據(jù)第一次來進(jìn)行適配的哦。
using UnityEngine;
using System.Collections;
#if UNITY_EDITOR
using UnityEditor;
#endifpublic enum QuadrantLayout{Quadrant1,Quadrant2,Quadrant3,Quadrant4
}[ExecuteInEditMode]
public class AutoLayout : MonoBehaviour{[HideInInspector] public QuadrantLayout quadrant;[HideInInspector] public Vector2 margin;Vector3 lastPostion;#if UNITY_EDITOR[HideInInspector] [SerializeField] private bool isFirstLoad=true;int pixelWidth;void Awake(){lastPostion = this.transform.localPosition;if(isFirstLoad){updateMarginOffset();isFirstLoad=false;}else{resetMarginOffset();}}void Update(){if(!Application.isPlaying){if(Vector3.Distance(lastPostion,this.transform.localPosition)>0.001f && Selection.activeGameObject == this.gameObject){updateMarginOffset();UnityEditor.EditorUtility.SetDirty(this);}else{resetMarginOffset();}lastPostion = this.transform.localPosition;}else{if((int)Camera.main.pixelWidth!=pixelWidth){resetMarginOffset();}pixelWidth = (int)Camera.main.pixelWidth;}}
#elsevoid Start(){resetMarginOffset();}
#endifvoid updateMarginOffset(){float m = (Camera.main.WorldToScreenPoint(new Vector3(1,0,0))-Camera.main.WorldToScreenPoint(Vector3.zero)).x;float halfWidth=Camera.main.pixelWidth/2.0f/m;float halfHeight=Camera.main.pixelHeight/2.0f/m;Vector3 v = this.transform.position;//1if(v.x>=0 && v.y>=0){quadrant = QuadrantLayout.Quadrant1;margin = new Vector2(halfWidth-v.x,halfHeight-v.y);//2}else if(v.x>=0 && v.y<=0){quadrant = QuadrantLayout.Quadrant2;margin = new Vector2(halfWidth-v.x,halfHeight+v.y);//3}else if(v.x<=0 && v.y<=0){quadrant = QuadrantLayout.Quadrant3;margin = new Vector2(halfWidth+v.x,halfHeight+v.y);//4}else if(v.x<=0 && v.y>=0){quadrant = QuadrantLayout.Quadrant4;margin = new Vector2(halfWidth+v.x,halfHeight-v.y);}}void resetMarginOffset(){Vector3 sv = Vector3.zero;float m = (Camera.main.WorldToScreenPoint(new Vector3(1,0,0))-Camera.main.WorldToScreenPoint(Vector3.zero)).x;float halfWidth=Camera.main.pixelWidth/2.0f/m;float halfHeight=Camera.main.pixelHeight/2.0f/m;switch(quadrant){case QuadrantLayout.Quadrant1:sv = new Vector3(halfWidth-margin.x,halfHeight-margin.y,0);break;case QuadrantLayout.Quadrant2:sv = new Vector3(halfWidth-margin.x,margin.y-halfHeight,0);break;case QuadrantLayout.Quadrant3:sv = new Vector3(margin.x-halfWidth,margin.y-halfHeight,0);break;case QuadrantLayout.Quadrant4:sv = new Vector3(margin.x-halfWidth,halfHeight-margin.y,0);break;}sv.z = this.transform.position.z;transform.position = sv;}
}
總結(jié)
以上是生活随笔為你收集整理的这里先发布一个,自己写得unityUI的适配的方案(插播)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。