Skip to content

Instantly share code, notes, and snippets.

@naojitaniguchi
Created September 30, 2015 07:35
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 naojitaniguchi/bf28682c4b795c2088fe to your computer and use it in GitHub Desktop.
Save naojitaniguchi/bf28682c4b795c2088fe to your computer and use it in GitHub Desktop.
Set UI Object position by corner and offset in Unity
using UnityEngine;
using System.Collections;
public class SetUIPos : MonoBehaviour {
public enum enumCorner { TopLeft, BottomLeft, TopRight, BottomRight };
public enumCorner coner;
public int offsetX;
public int offsetY;
// Use this for initialization
void Start () {
RectTransform rt = this.GetComponent<RectTransform>();
int xPos = 0;
int yPos = 0;
switch( coner)
{
case enumCorner.TopLeft:
{
xPos = -1 * Screen.width / 2 + ( (int)rt.sizeDelta.x / 2 + offsetX );
yPos = Screen.height / 2 - ( (int)rt.sizeDelta.y / 2 + offsetY );
break;
}
case enumCorner.BottomLeft:
{
xPos = -1 * Screen.width / 2 + ((int)rt.sizeDelta.x / 2 + offsetX);
yPos = -1 * Screen.height / 2 + ((int)rt.sizeDelta.y / 2 + offsetY);
break;
}
case enumCorner.TopRight:
{
xPos = Screen.width / 2 - ((int)rt.sizeDelta.x / 2 + offsetX);
yPos = Screen.height / 2 - ((int)rt.sizeDelta.y / 2 + offsetY);
break;
}
case enumCorner.BottomRight:
{
xPos = Screen.width / 2 - ((int)rt.sizeDelta.x / 2 + offsetX);
yPos = -1 * Screen.height / 2 + ((int)rt.sizeDelta.y / 2 + offsetY);
break;
}
}
rt.anchoredPosition = new Vector2((float)xPos, (float)yPos);
}
// Update is called once per frame
void Update () {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment