Unity检视面板的继承方法研究 (二)

  之前做了普通对象的可继承的检视面板类, 现在想要实现对Unity自带的检视面板的继承的话, 要怎样写呢?

  万变不离其宗,  仍然是围绕UnityEditor.Editor.CreateEditor 这个函数来实现:

    /// <summary>
    /// decorate Unity's built-in inspector Editor.
    /// </summary>
    public class DecoratorEditor<T> : UnityEditor.Editor
    {
        protected T _target;
        protected UnityEditor.Editor _nativeEditor;

        public void OnEnable()
        {
            _target = (T)System.Convert.ChangeType(target, typeof(T));

            Type targetEditorType = null;
            foreach(Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                var tempT = assembly.GetType("UnityEditor." + typeof(T).Name + "Inspector");
                if(tempT != null)
                {
                    targetEditorType = tempT;
                    break;
                }
            }
            if(targetEditorType != null)
            {
                _nativeEditor = UnityEditor.Editor.CreateEditor(serializedObject.targetObject, targetEditorType);
            }
            else
            {
                _nativeEditor = UnityEditor.Editor.CreateEditor(serializedObject.targetObject);
            }
        }

        public override void OnInspectorGUI()
        {          
            if(_nativeEditor != null)
            {
                _nativeEditor.OnInspectorGUI();
            }
        }
    }

  这里对于内置Unity Inspector的类型查找几乎是在走钢丝, 也只能碰运气了, 好在我只用来修改了一下TextureImporter的检视面板, 因为Unity2019里面没有显示spritePackingTag这个设置了, 可是这个序列化仍然存在.

#if UNITY_2019_1_OR_NEWER
    [CustomEditor(typeof(TextureImporter))]
    public class TextureImporterCustomEditor : DecoratorEditor<TextureImporter>
    {
        public override void OnInspectorGUI()
        {
            if(_target.textureType == TextureImporterType.Sprite)
            {
                _target.spritePackingTag = EditorGUILayout.TextField("Packing Tag", _target.spritePackingTag);
            }
            base.OnInspectorGUI();
        }
    }
#endif

  这样我的设置又回来了.

猜你喜欢

转载自www.cnblogs.com/tiancaiwrk/p/11418387.html