こんにちは、ユーゴです。
今回は、2021.2.10fを使用していたときに発生したPropertyFieldの2重描画バグについて共有します。おかしいな?と思った方の役に立てば幸いです。
なお、最新版の2021.3.3f(2022/5/26現在)では解消されている問題なので、2021.2系から2021.3系に上げてしまえば解決します。なので、バグレポートの方は必要ないかと思います。
1.環境
以下の環境で発生しました。
・Windows10
・Unity 2021.2.10f
また、発生しなかったバージョンは以下です。
・Unity 2019.4.32f
・Unity 2020.3.28f
・Unity 2021.3.3f
2.具体的な事象
結論から言うと、本来1枚目のように描画されるところ、2枚目のようにヘルプボックスが2重描画されました。
原因は不明です。
使用したプログラムは、以下2つです。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace YugoInspector
{
public class HelpBoxAttribute : PropertyAttribute
{
public MessageType messageType;
public string text;
public float height;
public HelpBoxAttribute(MessageType messageType,string text,float height)
{
this.messageType = messageType;
this.text = text;
this.height = height;
}
}
#if UNITY_EDITOR
[CustomPropertyDrawer(typeof(HelpBoxAttribute))]
public class HelpBoxEditor : PropertyDrawer
{
HelpBoxAttribute _attribute;
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
_attribute = attribute as HelpBoxAttribute;
var pos1 = new Rect(position.x, position.y, position.width, _attribute.height);
EditorGUI.HelpBox(pos1, _attribute.text,_attribute.messageType);
var pos2 = new Rect(position.x, position.y + _attribute.height, position.width, position.height - _attribute.height);
EditorGUI.PropertyField(pos2,property, label);
}
public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
{
_attribute = attribute as HelpBoxAttribute;
return base.GetPropertyHeight(property, label)+_attribute.height;
}
}
#endif
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using YugoInspector;
public class AttributeTest : MonoBehaviour
{
[HelpBox(UnityEditor.MessageType.None,"OK",20)]
public float f=2;
}
HelpBoxだけでなく、LabelFieldもダメでした。それ以外は試してませんが、2/2でアウトなのでダメな気がします。
また、EditorGUIだけでなく、EditorGUILayoutでも発生しました。最も、PropertyDrawerにEditorGUILayoutを使用するのは確か2021から許されたので、原則使用しない方がいいでしょう。
余談ですが、EditorGUILayoutはエディタ拡張、EditorGUIはカスタム属性という組み合わせが原則だと考えています。時間があれば、エディタ拡張とカスタム属性の違い・共存についても書こうと思います。
3.解決策
先述の通り、バージョンを変更する他なさそうです。コードの記述順を変えたり、EditorGUILayoutならどうだと試したわけですが、ダメでした。
LTSの2021.3系にするのが一番いいですが、会社で使ってて迂闊にバージョン上げられない...ということもあると思うので、別の解決策があればぜひ教えてください。
4.まとめ
いかがでしたでしょうか。Unityのバージョンを上げるときに、警告は出るけど「どうせ何も起きないでしょう!」と高を括っていると、インスペクタが壊れたりするわけです。バージョンを上げる際には、しっかりと動作を確認し、不具合込みで許容できるかを検討しましょう。
私の記事では、このようにUnityのコアでニッチな記事から、初心者向けの記事も書いていこうと思っています。
よろしければ、フォローの方お願いします。