zoukankan      html  css  js  c++  java
  • [UnityAPI]SerializedObject类 & SerializedProperty类

    以Image类为例

    1.MyImage.cs

     1 using UnityEngine;
     2 using UnityEngine.UI;
     3 
     4 public class MyImage : Image {
     5 
     6     private int a = 1;
     7     protected float b = 2f;
     8     public string c = "3";
     9     public int D { get; set; }
    10 
    11     protected override void OnPopulateMesh(VertexHelper toFill)
    12     {
    13         base.OnPopulateMesh(toFill);
    14 
    15         Debug.Log(a);
    16         Debug.Log(b);
    17         Debug.Log(c);
    18         Debug.Log(D);
    19     }
    20 }

    MyImage继承自Image,但是如果把MyImage挂上去,会发现面板上没有出现自定义的属性,这是为什么呢?通过看UGUI的源码,可以发现有一个ImageEditor类,这个类负责绘制Image的属性面板,同时还存在这样一句:[CustomEditor(typeof(Image), true)],表示所有继承自Image的子类都使用和Image一样的属性面板。

    2.MyImageEditor.cs

    那么,如果想让Image的子类显示出自定义的属性,该怎么办呢?很简单,写一个类去继承ImageEditor,然后去绘制自定义的属性即可。参考ImageEditor的源码可以得出如下代码。serializedObject为被序列化的对象,SerializedProperty为该对象上被序列化的字段。经测试,private和protected的字段要加上[SerializeField]才能被序列化,public的字段无需处理,而属性是不能被serializedObject.FindProperty(会报空)

     1 using UnityEditor.UI;
     2 using UnityEditor;
     3 
     4 [CustomEditor(typeof(MyImage))]
     5 [CanEditMultipleObjects]
     6 public class MyImageEditor : ImageEditor {
     7 
     8     SerializedProperty a;
     9     SerializedProperty b;
    10     SerializedProperty c;
    11     SerializedProperty D;
    12 
    13     protected override void OnEnable()
    14     {
    15         base.OnEnable();
    16 
    17         a = serializedObject.FindProperty("a");
    18         b = serializedObject.FindProperty("b");
    19         c = serializedObject.FindProperty("c");
    20         D = serializedObject.FindProperty("D");
    21     }
    22 
    23     public override void OnInspectorGUI()
    24     {
    25         base.OnInspectorGUI();
    26 
    27         serializedObject.Update();
    28 
    29         EditorGUILayout.PropertyField(a);
    30         EditorGUILayout.PropertyField(b);
    31         EditorGUILayout.PropertyField(c);
    32         //EditorGUILayout.PropertyField(D);
    33 
    34         serializedObject.ApplyModifiedProperties();
    35     }
    36 }

    效果如下:

  • 相关阅读:
    基于jquery的web在线流程图设计器gooFlow
    angularJS学习笔记二
    angularJS学习笔记一
    JavaScript作用域链详解
    图片查看器(可拖拽,缩放,轮播)
    小议window.event || ev
    Vue安装准备工作
    让VS2013添加新类时自动添加public关键字
    win10太垃圾,真的不好用。
    Bind 和 ScaffoldColumn[转]
  • 原文地址:https://www.cnblogs.com/lyh916/p/10659220.html
Copyright © 2011-2022 走看看