Created
September 30, 2015 07:35
-
-
Save naojitaniguchi/bf28682c4b795c2088fe to your computer and use it in GitHub Desktop.
Set UI Object position by corner and offset in Unity
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; | |
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