Last active
August 29, 2015 14:05
-
-
Save tsubaki/d7818fe001a79c0d67df to your computer and use it in GitHub Desktop.
letterbox like interface in uGUI (screen space)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
using UnityEngine.UI; | |
[RequireComponent(typeof(ReferenceResolution))] | |
[ExecuteInEditMode] | |
public class LetterBoxScreenSpace : MonoBehaviour { | |
public RectTransform rootRectTransform; | |
private ReferenceResolution refreso; | |
public ReferenceResolution RefReso | |
{ | |
get{ | |
if( refreso == null ) | |
refreso = GetComponent<ReferenceResolution>(); | |
return refreso; | |
} | |
} | |
float aspect = 0; | |
void Start() | |
{ | |
UpdateResolution(); | |
} | |
#if UNITY_EDITOR | |
void Update () | |
{ | |
if( !UnityEditor.EditorApplication.isPlaying ) | |
{ | |
UpdateResolution(); | |
} | |
} | |
#endif | |
void UpdateResolution() | |
{ | |
if( rootRectTransform == null) | |
{ | |
Debug.LogWarning("set root RectTransform"); | |
return; | |
} | |
var physicalAspect = (float)Screen.height / Screen.width; | |
if( aspect == physicalAspect ) | |
return; | |
aspect = physicalAspect; | |
rootRectTransform.sizeDelta = RefReso.resolution; | |
var referenceAspect = (float)RefReso.resolution.y / RefReso.resolution.x; | |
RefReso.matchWidthOrHeight = (physicalAspect > referenceAspect)? 0 : 1; | |
} | |
[ContextMenu("Set Up")] | |
void Init() | |
{ | |
var childList = GetComponentsInChildren<RectTransform>(); | |
if( rootRectTransform != null ) | |
{ | |
return; | |
} | |
var obj = new GameObject("root", typeof(RectTransform)); | |
var rt = obj.GetComponent<RectTransform>(); | |
rootRectTransform = rt; | |
rt.SetParent(transform); | |
rt.transform.localScale = new Vector3(1,1,1); | |
rt.anchoredPosition = new Vector2(0,0); | |
var currentRectTransform = GetComponent<RectTransform>(); | |
foreach( var child in childList ) | |
{ | |
if( child != currentRectTransform) | |
child.SetParent(rt, false); | |
} | |
UpdateResolution(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
使い方
Canvasにアタッチしてset upコンテキストを実行する。