Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@tsubaki
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tsubaki/bb63756024ccccbca48d to your computer and use it in GitHub Desktop.
Save tsubaki/bb63756024ccccbca48d to your computer and use it in GitHub Desktop.
letterbox like interface in uGUI
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
[RequireComponent(typeof(Canvas))]
[ExecuteInEditMode]
public class LetterBox : MonoBehaviour
{
// UI camera
public Camera targetCamera;
// resolution
public Vector2 screenSize = new Vector2(800, 600);
private float aspect;
private Canvas targetCanvos;
void Start()
{
UpdateResolution();
}
#if UNITY_EDITOR
void Update ()
{
if(! UnityEditor.EditorApplication.isPlaying)
{
UpdateResolution();
}
}
#endif
void OnValidate()
{
UpdateResolution();
}
private Canvas TargetCanvas
{
get
{
if( targetCanvos == null )
targetCanvos = GetComponent<Canvas>();
return targetCanvos;
}
}
float GetAspect()
{
return (float)Screen.height / Screen.width;
}
void UpdateResolution()
{
if( targetCamera == null || TargetCanvas == null )
{
Debug.LogWarning("camera or canvous is not reference");
return;
}
// if same aspect as cash, skip.
float currentAspect = GetAspect();
if( currentAspect == aspect )
{
return;
}
aspect = currentAspect;
// update resolution
TargetCanvas.renderMode = RenderMode.World;
TargetCanvas.worldCamera = targetCamera;
TargetCanvas.transform.localScale = new Vector3(1,1,1);
var rectT = TargetCanvas.GetComponent<RectTransform>();
rectT.sizeDelta = screenSize;
var referenceScreenRate = screenSize.y / screenSize.x;
var physicalScreenRate = aspect;
var diffScreenRate = physicalScreenRate / referenceScreenRate;
var heightHalf = screenSize.y * 0.5f;
targetCamera.orthographicSize =
(diffScreenRate > 1) ? heightHalf * diffScreenRate : heightHalf;
}
void CreateUICamera()
{
transform.parent = null;
DestroyImmediate ( GameObject.Find("UI Camera"));
var uiCamera = new GameObject("UI Camera");
uiCamera.transform.localPosition =
transform.position + transform.forward * -10;
var cam = uiCamera.AddComponent<Camera>();
cam.cullingMask = 1 << LayerMask.NameToLayer("UI");
cam.clearFlags = CameraClearFlags.Depth;
cam.isOrthoGraphic = true;
cam.depth = 99;
targetCamera = cam;
transform.parent = targetCamera.transform;
}
[ContextMenu("set up")]
void Init()
{
targetCanvos = GetComponent<Canvas>();
if( targetCamera == null )
CreateUICamera();
UpdateResolution();
}
}
@tsubaki
Copy link
Author

tsubaki commented Aug 31, 2014

How to use

  1. Add LetterBox component to canvaus.
  2. Click context menu "set up”.

work

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment