Unity3d屏幕分辨率自适应问题
Posted 小小灵爱李婷
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity3d屏幕分辨率自适应问题相关的知识,希望对你有一定的参考价值。
解决屏幕分辨率的脚本主要有2个(UIAdapt,ScaleAdapt)
1.UIAdapt脚本
using UnityEngine;
using System.Collections;
/// <summary>
/// 单例类 ,不用挂载
/// </summary>
public class UIAdapt {
private static UIAdapt _instance;
private static object _lock=new object();
public static UIAdapt Instance
{
get
{
lock (_lock)
{
if (_instance == null)
{
_instance = new UIAdapt();
}
return _instance;
}
}
}
float originWidth = 1334;
float originHeight = 750;
float lastWidth;
float lastHeight;
Vector2 nowHW = new Vector2();
public Vector2 GetNowHW()
{
if (Screen.width == lastWidth && Screen.height == lastHeight) return nowHW;
float ratioHW = originHeight / originWidth;
int height =(int)( Screen.width *ratioHW);
int width=0;
if(height>Screen.height)
{
height = Screen.height;
width =(int)(height / ratioHW);
}
else
{
width = Screen.width;
}
nowHW.x = width;
nowHW.y = height;
lastHeight = Screen.height;
lastWidth = Screen.width;
return nowHW;
}
public float GetScale()
{
Vector2 hw = GetNowHW();
float yScale = hw.y / originHeight;
float xScale = hw.x / originWidth;
return yScale > xScale ? xScale : yScale;
}
}
2.ScaleAdapt脚本
using UnityEngine;
using System.Collections;
public class ScaleAdapt : MonoBehaviour {
[SerializeField]
public enum HorizontalAdaptiveMode
{
NONE,
LEFT,
RIGHT
}
[SerializeField]
public enum VerticalAdaptiveMode
{
NONE,
UP,
DOWN
}
public HorizontalAdaptiveMode horMode = HorizontalAdaptiveMode.NONE;
public VerticalAdaptiveMode verMode = VerticalAdaptiveMode.NONE;
Vector2 startVector;
Vector2 lastVector;
public Vector2 nowHW;
UIPanel panel;
void Awake()
{
// panel = GameObject.FindGameObjectWithTag("GuiCamera").transform.parent.GetComponent<UIPanel>();
}
void Start () {
startVector = transform.localScale;
Adaptive();
}
#if UNITY_EDITOR
void Update ()
{
Adaptive();
}
#endif
Vector3 finScale;
void Adaptive()
{
nowHW = UIAdapt.Instance.GetNowHW();
float ratio=UIAdapt.Instance.GetScale();
if (lastVector == nowHW) return;
lastVector = nowHW;
finScale.x = startVector.x * ratio;
finScale.y = startVector.y * ratio;
finScale.z = finScale.x;
transform.localScale = finScale;
Vector3 offset = Vector3.zero;
int dir = 0;
if(horMode!=HorizontalAdaptiveMode.NONE)
{
dir = horMode == HorizontalAdaptiveMode.LEFT ? -1 : 1;
// offset += dir * Vector3.right * (panel.width - nowHW.x) / 2;
offset += dir * Vector3.right * (Screen.width - nowHW.x) / 2;
}
if(verMode!=VerticalAdaptiveMode.NONE)
{
dir = verMode == VerticalAdaptiveMode.DOWN ? -1 : 1;
// offset += dir * Vector3.up * (panel.height - nowHW.y) / 2;
offset += dir * Vector3.up * (Screen.height - nowHW.y) / 2;
}
transform.localPosition = offset;
}
}
以上是关于Unity3d屏幕分辨率自适应问题的主要内容,如果未能解决你的问题,请参考以下文章