2014年4月22日火曜日

Unityで属性を自作する方法

クラスメンバなどに自作の属性を使用する方法。
  1. PropertyAttributeを継承したクラスを作成する(クラス名が属性、コンストラクタが引数)
  2. CustomPropertyDrawerを属性につけたクラス(PropertyDrawerを継承) を作成。
  3. OnGUIをオーバーライドし、内部でGUIの描画処理を行う。
プロパティを使用するクラス
using UnityEngine;
using System.Collections;

public class Test : MonoBehaviour {

 [Lenge(0,100)]
 public float hp = 0;
}

属性を設定するクラス
using UnityEngine;
using System.Collections;
using UnityEngine;

public class Lenge : PropertyAttribute
{
 public float min;
 public float max;

 public Lenge(float min, float max)
 {
  this.min = min;
  this.max = max;
 }
}

GUIを描画するクラス
using UnityEngine;
using System.Collections;
using UnityEditor;

[CustomPropertyDrawer(typeof(Lenge))]
public class Editor : PropertyDrawer
{
 public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
 {
  Lenge len = (Lenge)attribute;
  EditorGUI.Slider(position, property, len.min, len.max, label);
 }
} 
するとこんな感じにプロパティにGUIが登場してくれる

0 件のコメント: