Is there any way to hide the “Object picker” of an EditorGUILayout.ObjectField in Unity Isnpector?

廉价感情. 提交于 2019-12-02 01:53:51
Quasimodo's clone

You might find a solution to hide the object picker by usage of stylesheets.

If all you want is just to display some reference, you can use a simple button basically styled as text field, adding an image and ping the object from code yourself.

using UnityEngine;

namespace Test
{
    public class TestBehaviour : MonoBehaviour
    {
        [SerializeField] private bool _audioEnabled;
        [SerializeField] private AudioClip _audioClip;
    }
}

editor:

using System.Reflection;
using UnityEditor;
using UnityEditor.Experimental.UIElements;
using UnityEngine;

namespace Test
{
    [CustomEditor(typeof(TestBehaviour))]
    public class TestBehaviourEditor : Editor
    {
        private SerializedProperty _clipProp;
        private SerializedProperty _audioEnabledProp;
        private ObjectField m_ObjectField;

        private const BindingFlags FIELD_BINDING_FLAGS = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

        private void OnEnable()
        {
            _clipProp = serializedObject.FindProperty("_audioClip");
            _audioEnabledProp = serializedObject.FindProperty("_audioEnabled");
        }

        public override void OnInspectorGUI()
        {
            serializedObject.Update();

            EditorGUILayout.PropertyField(_audioEnabledProp);

            if(_audioEnabledProp.boolValue)
                EditorGUILayout.PropertyField(_clipProp);
            else
            {
                //TODO: calculate proper layout 

                var type = target.GetType().GetField(_clipProp.propertyPath, FIELD_BINDING_FLAGS).FieldType;
                var clip = _clipProp.objectReferenceValue;

                var guiContent = EditorGUIUtility.ObjectContent(clip, type);

                EditorGUILayout.BeginHorizontal();
                EditorGUILayout.LabelField("Fake ObjectField Button");

                var style = new GUIStyle("TextField");
                style.fixedHeight   = 16;
                style.imagePosition = clip ? ImagePosition.ImageLeft : ImagePosition.TextOnly;


                if (GUILayout.Button(guiContent, style ) && clip)
                    EditorGUIUtility.PingObject(clip);

                EditorGUILayout.EndHorizontal();
            }

            serializedObject.ApplyModifiedProperties();
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!