LoginSignup
7
9

More than 5 years have passed since last update.

【Unityエディタ拡張】Prefab以外アタッチできなくするPropertyDrawerを自作する

Last updated at Posted at 2016-07-28

はじめに

変数にpublicやSerializeField属性をつけると、Inspectorからオブジェクトをアタッチすることが
できるようになります.

ただ、Prefabを扱うつもりで用意した変数に間違えてScene内のオブジェクトをアタッチしてしまう、といったヒューマンエラーが発生する危険があります.

そこで、Prefab以外をアタッチしたら勝手に外れるPropertyDrawerを作ってみました。

どんなことができるの?

NewBehaviourScript.cs
using UnityEngine;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour
{
    [PrefabField]
    public GameObject hoge;
}

public変数の直前に [PrefabField] と書くことでその変数にPrefab以外のオブジェクトをアタッチすることが
できなくなります。 Prefab以外のオブジェクトをアタッチしても勝手に外れるようになります。

ソースコード

まず、以下のスクリプトを作成してプロジェクトに入れます。

PrefabFieldAttribute.cs
using UnityEngine;

public class PrefabFieldAttribute : PropertyAttribute
{
}

次に以下のスクリプトを作成してEditorフォルダ内に入れます.

PrefabFieldDrawer.cs
using UnityEngine;
using UnityEditor;

[CustomPropertyDrawer(typeof(PrefabFieldAttribute))]
public class PrefabFieldDrawer : PropertyDrawer
{
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        if (property.objectReferenceValue != null)
        {
            var prefabType = PrefabUtility.GetPrefabType(property.objectReferenceValue);
            switch (prefabType)
            {
                case PrefabType.Prefab:
                case PrefabType.ModelPrefab:
                    break;
                default:
                    // Prefab以外がアタッチされた場合アタッチを外す
                    property.objectReferenceValue = null;
                    break;
            }
        }

        label.text += " (Prefab Only)";
        EditorGUI.PropertyField(position, property, label);
    }
}

以上で完了となります。

実行結果

変数名の表記が Hoge から Hoge (Prefab Only) となります。
image
ここにはPrefabを入れればいいんだな? ということがエディター上から読み取れるようになります。(ヒューマンエラー防止)



Prefab以外のオブジェクトをアタッチしても勝手に外れます
prefab.gif



Prefabの場合はアタッチできます
prefab2.gif

参考

自分だけのPropertyDrawerを作ろう!
http://qiita.com/kyusyukeigo/items/8be4cdef97496a68a39d

7
9
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
7
9