3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Unity】 ScrollBarをScrollRect.verticalNormalizedPositionを使ってスティックで操作する

Last updated at Posted at 2019-07-25

概要

マウスを使わずに、コントローラーの入力でuGUIのスクロールを行う記事を探したが、見つからず、試行錯誤した結果成功したので、まとめることにしました。誰かの役に立つことを願います。

まず初めに断っておきますが、縦スクロールの挙動しか検証していません。
横も理論上同じ動作ができるはずですが、未検証のため今回は縦スクロールの方法のみを紹介します

手順

ヒエラルキーにuGuIのCavasを作成し、ScrollViewを作成します。
次に、ScrollRectのHorizontalのチェックをはずします。

縦スクロールのみ必要なので、Scrollbar Horizontalを消します。

次に以下のスクリプトを作成し、ScroolViewにアタッチします。

ScrollBar.cs
using UnityEngine;

using System.Collections;

using UnityEngine.UI;

public class ScrollBar : MonoBehaviour {
     public ScrollRect ScrollRect;

    void Update()
    {
        float v = Input.GetAxis("Vertical");

        if(Input.GetAxis("Vertical") != 0 )
        {
            if(Input.GetAxis("Vertical") <= 0 )
            {
                ScrollRect.verticalNormalizedPosition = Mathf.Lerp(ScrollRect.verticalNormalizedPosition, v, 0.01f);
            }


           if(Input.GetAxis("Vertical") >= 0 )
           {
               ScrollRect.verticalNormalizedPosition = Mathf.Lerp(ScrollRect.verticalNormalizedPosition, v+1, 0.01f);
           }
        }
    }

解説

縦の入力値をvに保存し、正と負の入力に応じてスクロールバーの位置を変更しています。
Mathf.Lerpをかけることで入力値を緩やかにしています。

正の入力の際に、vに+1しているのは、スクロールバーの上限と下限が1と0に対し、入力値は1と-1のため、
1,1の間を補完させるとスクロールバーが端に行くほど動きが遅くなるため、+1をして1と2の間を補完するようにしています。

手順続き

アタッチしたスクリプトのScrollRectのインスペクタに、ScrollViewのScrollRectをドラッグ&ドロップします。
これでシーンを再生すると、スクロールバーをVerticalの入力で動かせるようになりました。

最終的にこのようなhierarchyになります。スクリーンショット (8).png

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?