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 }

    效果如下:

  • 相关阅读:
    __str__和__repr__
    面向对象进阶实战之选课系统
    面向对象总结
    反射(hasattr和getattr和setattr和delattr)
    类和对象的绑定方法及非绑定方法
    -bash: mysql: command not found 解决办法 (转)
    C++类的const成员函数、默认的构造函数、复制形参调用函数(转)
    Zend Framework学习日记(2)--HelloWorld篇(转)
    Zend Framework学习日记(1)--环境搭建篇(转)
    用C/C++扩展你的PHP(转)
  • 原文地址:https://www.cnblogs.com/lyh916/p/10659220.html
Copyright © 2011-2022 走看看