LoginSignup
11
12

More than 5 years have passed since last update.

画面の端にUIを表示させる【Unity, uGui】

Last updated at Posted at 2015-08-02

uGuiのボタンなどを画面端に固定して表示させます。

スクリプト

左・中央・右、上・中央・下の画面端に固定させることが出来ます。
このスクリプトをuGUIのゲームオブジェクトにアタッチします。

UGuiPositionSetter
using UnityEngine;
using System.Collections;

public class UGuiPositionSetter : MonoBehaviour {
    public enum PositionX {
        LEFT,
        CENTER,
        RIGHT,
        FREE
    };
    public enum PositionY {
        TOP,
        MIDDLE,
        BOTTOM,
        FREE
    };

    [SerializeField]
    public PositionX positionX = PositionX.FREE;
    [SerializeField]
    public PositionY positionY = PositionY.FREE;
    public bool isUpdate = false;

    public Vector2 margin;

    private RectTransform _rt;

    void Start () {
        _rt =  GetComponent<RectTransform>();
    }

    void Update () {
        if (isUpdate)
            setPosition();
    }

    private void setPosition() {
        Vector2 pos = _rt.anchoredPosition;
        switch (positionX) {
        case PositionX.CENTER:
            pos.x = 0f;
            break;
        case PositionX.LEFT:
            pos.x = - Screen.width * 0.5f + _rt.rect.width * 0.5f + margin.x;
            break;
        case PositionX.RIGHT:
            pos.x = Screen.width * 0.5f - _rt.rect.width * 0.5f - margin.x;
            break;
        }

        switch (positionY) {
        case PositionY.MIDDLE:
            pos.y = 0f;
            break;
        case PositionY.BOTTOM:
            pos.y = - Screen.height * 0.5f + _rt.rect.height * 0.5f + margin.y;
            break;
        case PositionY.TOP:
            pos.y = Screen.height * 0.5f - _rt.rect.height * 0.5f - margin.y;
            break;
        }
        _rt.anchoredPosition = pos;
    }
}

使い方

使い方はこんな感じ。
プルダウンで場所を選ぶとそこに固定される。
スクリーンショット 2015-08-02 19.25.56.png

結果

今回は左上にボタンを固定配置させています。
スクリーンショット 2015-08-02 19.25.47.png

11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12