2012年4月1日日曜日

Unity ギズモの描画と編集

空のゲームオブジェクトにTestGizmo.csを追加

ギズモを選択、編集タイプに応じて移動、サイズ変更がシーンウィンドウで行える

Assets/Script/TestGizmo.cs

using UnityEngine;

// ギズモのテスト用クラス
public class TestGizmo : MonoBehaviour {
  // 編集タイプの種類
  public enum EditType {
    Invalid,
    BoundCenter,
    BoundSize
  }

  // 編集タイプ
  public EditType editType = EditType.Invalid;

  // ギズモの形状
  public Bounds   bound = new Bounds(Vector3.zero, Vector3.one);

  // ギズモの描画
  void OnDrawGizmos () {
    Gizmos.color = Color.magenta;
    Gizmos.DrawWireCube(bound.center, bound.size);
  }
}

Assets/Editor/EditorTestGizmo.cs

using UnityEngine;
using UnityEditor;

// TestGizmoの編集用クラス
[CustomEditor( typeof(TestGizmo) )]     // ←編集対象のクラスを指定
public class EditorTestGizmo : Editor {

  // Editor.OnSceneGUI シーンウィンドウ上のGUI処理
  void OnSceneGUI () {
    // 編集対象を取得
    TestGizmo t = target as TestGizmo;

      switch(t.editType) {
      case TestGizmo.EditType.BoundCenter:
          // 位置の変更
          t.bound.center = Handles.PositionHandle(t.bound.center, 
                                      Quaternion.identity);
          break;
      case TestGizmo.EditType.BoundSize:
          // サイズの変更
          t.bound.size = Handles.ScaleHandle(t.bound.size, 
                           t.bound.center, Quaternion.identity, 5.0f);
          break;
      }
      if (GUI.changed) {
//          Debug.Log("GUI.changed");
      }
  }
}