Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
letterbox like interface in uGUI (screen space)
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();
}
}
@tsubaki

This comment has been minimized.

Copy link
Owner Author

@tsubaki tsubaki commented Sep 1, 2014

使い方

Canvasにアタッチしてset upコンテキストを実行する。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.