首页 > 代码库 > 这里先公布一个,自己写得unityUI的适配的方案(插播)
这里先公布一个,自己写得unityUI的适配的方案(插播)
这个适配是根据坐标系的象限的思想来进项适配的,参考了部分的NGUI的适配方案。
在程序的其实,来测量UI距离相机边界的像素然后根据比例来进行适配,个人觉得还不错。 放码!。
有个前提哦就是你要先定一个尺寸。假如我优先适配1024*768。那在放置这个脚本之前,要把自己的界面还成1024*768的哦。我是根据第一次来进行适配的哦。
using UnityEngine; using System.Collections; #if UNITY_EDITOR using UnityEditor; #endif public 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; } } #else void Start(){ resetMarginOffset(); } #endif void 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; //1 if(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; } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。