LoginSignup
2
2

More than 5 years have passed since last update.

[Unity]サイズをシーン上で変えられるGrid

Last updated at Posted at 2017-02-09

結果

Grid.gif

GridLayoutGroupの問題点

GridLayoutGroupにはCellのサイズをScene上で調整できない

スクリプト

using UnityEngine;
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
#endif

/// <summary>
/// Scene上でGridのサイズを変更できるようにする拡張
/// </summary>
public class CustomGrid : GridLayoutGroup {
    #if UNITY_EDITOR
    // 子のRectTransformを更新するタイミング
    public override void SetLayoutHorizontal ()
    {
        UpdateCellSize ();
        base.SetLayoutHorizontal ();
    }

    // CellSizeを更新
    void UpdateCellSize(){
        // シーン上のオブジェクトであるか
        var obj = Selection.activeGameObject;
        if (!obj) {
            return;
        }

        // RectTransformを持っているか
        var tran = obj.GetComponent<RectTransform> ();
        if (!tran) {
            return;
        }

        // 親が自身であるか
        if (tran.parent == this.transform) {
            cellSize = new Vector2 (tran.rect.width, tran.rect.height);
        }
    }
    #endif
}
2
2
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
2
2