1. 程式人生 > >Unity3d屏幕分辨率自適應問題

Unity3d屏幕分辨率自適應問題

mod tar turn ets ins osi endif lse 3D

解決屏幕分辨率的腳本主要有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屏幕分辨率自適應問題