Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
12
Help us understand the problem. What is going on with this article?
@kwst

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

More than 5 years have passed since last update.

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

12
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
kwst
Front Engineer

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
12
Help us understand the problem. What is going on with this article?