文档

Unity 引擎

Unity 引擎

使用 PropertyVisitor 类创建属性访问者

了解如何通过示例使用 PropertyVisitor 类建属性访问者。
阅读时间12 分钟最后更新于 6 天前

此示例演示如何使用
PropertyVisitor
底部类来创建属性访问者。有关使用
IPropertyBagVisitor
和
IPropertyVisitor
接口的等效示例,请参阅使用低关卡 API 创建属性访问者。

创建数据和 Utility 类

创建一个Simple的数据类和一个Utility程序类,使用访问者访问和打印Properties性:
  1. 创建以下名为
    Data
    的 C# 类及其可访问的属性:
    using System.Collections.Generic;using UnityEngine;public class Data{ public string Name = "Henry"; public Vector2 Vec2 = Vector2.one; public List<Color> Colors = new List<Color> { Color.green, Color.red }; public Dictionary<int, string> Dict = new Dictionary<int, string> { { 5, "zero" } };}
  2. 创建以下名为
    DebugUtilities
    的 Utility 类:
    using UnityEngine;public static class DebugUtilities{ public static void PrintObjectDump<T>(T value) { // Magic goes here. }}

创建访问者

按如下方式创建访问者类:
  1. 创建继承自
    PropertyVisitor
    的名为
    ObjectVisitor
    的类。
  2. 向类添加
    StringBuilder
    Field。此版本可用于表示 Object 当前状态的字符串。
  3. 添加清除
    StringBuilder
    并重置缩进关卡的
    Reset
    方法。
  4. 添加一个
    GetDump
    方法,返回对象当前状态的字符串表示。
    ObjectVisitor
    类现在如下所示:
    // `PropertyVisitor` is an abstract class that you must derive from. public class ObjectVisitor:PropertyVisitor{ private const int k_InitialIndent = 0; private 只读 StringBuilder m_构建器 = 新建 StringBuilder(); private 整型 m_IndentLevel = k_InitialIndent; private 字符串 Indent => 新建 (' ', m_IndentLevel * 2); public void Reset() { m_Builder.Clear(); m_IndentLevel = k_InitialIndent; } public string GetDump() { return m_Builder.ToString(); }}

获取顶级属性

在
ObjectVisitor
类中,重载
VisitProperty
方法以访问 Object 的每个属性并日志记录属性 Name。该
PropertyVisitor
不需要 Any 成员来实现,默认情况下,它只是访问每个属性而不执行任何 Action。
  1. 在
    ObjectVisitor
    类中,添加以下重载
    VisitProperty
    方法:
    protected override void VisitProperty<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value){ m_Builder.AppendLine($"- {property.Name}");}
  2. 现在有了最少的访问者,就可以实现 Utility 方法。更新
    DebugUtilities
    类中的
    PrintObjectDump
    方法以创建新的
    ObjectVisitor
    实例并使用它访问给定对象的 Properties:
    public static class DebugUtilities{ private Static 只读 ObjectVisitor s_Visitor = 新建(); public static void PrintObjectDump<T>(T value) { s_Visitor.Reset(); // This is the main entry point to run a visitor. PropertyContainer.Accept(s_Visitor, ref value); Debug.Log(s_Visitor.GetDump()); }}
  3. 从代码的适当位置调用
    PrintObjectDump
    方法并向其通道一个
    Data
    Object。例如,从 Simple MonoBehaviour 组件中,这可能如下所示:
    using UnityEngine;public class MyMonoBehaviour :MonoBehaviour{ void Start() { DebugUtilities.PrintObjectDump(new Data()); }}
    这会将以下输出打印到控制台:
    "name":- Vec2- 颜色- Dict

获取子属性

如上一部分的输出所示,重载
VisitProperty
方法时,它不会自动访问对象的子 Properties。要获取子 Properties,请使用
PropertyContainer.Accept
方法以递归方式将访问器应用于每个值。
在
ObjectVisitor
类中,更新
VisitProperty
方法以递归方式将访问者应用于要嵌套的值:
protected override void VisitProperty<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value){ m_Builder.AppendLine($"{Indent}- {property.Name}"); ++m_IndentLevel; // Apply this visitor recursively on the value to nest in. if (null != value) PropertyContainer.Accept(this, ref value); --m_IndentLevel;}
控制台输出在如下所示:
"name":- Vec2xy- 颜色- 0 -R g: - b A- 1 -R g: - b A - Dict- 5 key "value": "",

显示有关每个属性的更多信息

要进一步增强打印输出,请获取Collection项的属性Name以及每个属性的类型值。某些Properties具有特殊的名称,尤其是WheCollectionollection。属性名称的约定如下:
  • 对于列表项,Name 对应于索引。
  • 对于字典,Name派生键值的字字符串版本。
  • 对于集,Name基ON值的字字符串版本。
为了make区别更加显式,请将属性Name称括在方括号中。
  1. 在
    ObjectVisitor
    类中,添加以下方法:
    private Static 字符串 GetPropertyName(IProperty 属性){ return property switch { // You can also treat `IListElementProperty`、`IDictionaryElementProperty` 和 `ISetElementProperty` 分开。 ICollectionElementProperty => $"[{property.Name}]", _ => property.Name };}
  2. 更新
    VisitProperty
    方法以使用
    TypeUtility.GetTypeDisplayName
    检索给定类型的 Display Name。
    protected override void VisitProperty<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value){ var propertyName = GetPropertyName(property); // Get the concrete type of the property or its declared type if value is null. var typeName = TypeUtility.GetTypeDisplayName(value?.GetType() ?? property.DeclaredValueType()); m_Builder.AppendLine($"{Indent}- {propertyName} = {{{typeName}}} {value}"); ++m_IndentLevel; if (null != value) PropertyContainer.Accept(this, ref value); --m_IndentLevel;}
    控制台输出在如下所示:
    - Name = {字符串} Henry- Vec2 = 二维向量 (1.00, 1.00)- x = {float} 1- y = {float} 1- Colors = <Color> System.Collections.Generic.列表`1[UnityEngine.Color]- [1] = {Color} RGBA(0.000, 1.000, 0.000, 1.000) - r = {float} 0 - g = {float} 1 - b = {float} 0 - a = {float} 1- [1] = {Color} RGBA(1.000, 0.000, 0.000, 1.000) - r = {float} 1 - g = {float} 0 - b = {float} 0 - a = {float} 1- Dict = {Dictionary<int, string>} System.Collections.Generic.Dictionary`2[System.Int32,System.字符串]- [5] = {KeyValuePair<int, string>} [5, five] - Key = {int} 5 - 值 = {string} 五

显示有关 Collection 类型的较少信息

由于
List<T>
不会重载
ToString()
方法,因此列表值显示为
System.Collections.Generic.List1[UnityEngine.Color]
。要减少显示的信息量,请更新
VisitProperty
以使用
TypeTraits.IsContainer
Utility 方法仅显示不包含子 Properties 的类型(例如图元、枚举和字符串)的值。
在
ObjectVisitor
类中,更新
VisitProperty
方法以使用
TypeTraits.IsContainer
确定该值是否为容器类型。如果是,则显示不带 值的类型 Name。否则,显示类型 Name 和 值:
protected override void VisitProperty<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value){ var propertyName = GetPropertyName(property); var type = value?.GetType() ?? property.DeclaredValueType(); var typeName = TypeUtility.GetTypeDisplayName(type); // Only display the values for primitives, enums and strings. if (TypeTraits.IsContainer(type)) m_Builder.AppendLine($"{Indent}- {propertyName} {{{typeName}}}"); else m_Builder.AppendLine($"{Indent}- {propertyName} = {{{typeName}}} {value}"); ++m_IndentLevel; if (null != value) PropertyContainer.Accept(this, ref value); --m_IndentLevel;}
控制台输出在如下所示:
- Name = {字符串} Henry- Vec2 二维向量}- x = {float} 1- y = {float} 1- 颜色<Color>**颜色** - r = {float} 0 - g = {float} 1 - b = {float} 0 - a = {float} 1**颜色** - r = {float} 1 - g = {float} 0 - b = {float} 0 - a = {float} 1- Dict {Dictionary<int, string>- [5] {KeyValuePair<int, string>} - Key = {int} 5 - 值 = {string} 五
提示
为了减少显示的信息量,还可以使用以下方法重载 Collection 类型的
Visit
专用化:
这些与
VisitProperty
方法类似,但它们公开了各自 Collections 类型的 Generic Parameters。

添加指定的类型覆盖

添加指定的类型覆盖以更紧凑的方式显示
Vector2
和
Color
类型。
将
PropertyVisitor
与
IVisitPropertyAdapter
一起使用。当为指定类型注册适配器时,如果在访问期间遇到目标类型,则会调用适配器而不是
VisitProperty
方法。
在
ObjectVisitor
类中,添加
Vector2
和
Color
的
IVisitPropertyAdapter
:
public class DumpObjectVisitor PropertyVisitor , IVisitPropertyAdapter<Vector2> , IVisitPropertyAdapter<Color>{ public DumpObjectVisitor() { AddAdapter(this); } void IVisitPropertyAdapter<Vector2>.Visit<TContainer>(in VisitContext<TContainer, Vector2> context, ref TContainer container, ref Vector2 value) { var propertyName = GetPropertyName(context.Property); m_Builder.AppendLine($"{Indent}- {propertyName} = {{{nameof(Vector2)}}} {value}"); } void IVisitPropertyAdapter<Color>.Visit<TContainer>(in VisitContext<TContainer, Color> context, ref TContainer container, ref Color value) { var propertyName = GetPropertyName(context.Property); m_Builder.AppendLine($"{Indent}- {propertyName} = {{{nameof(Color)}}} {value}"); }}

开始访问子属性

当您运行 ON 数据访问者时,默认情况下,它会启动顶部关卡对象的访问。对于 Any 属性访问者,要开始访问对象的子 Properties,请向
PropertyContainer.Accept
方法通道
PropertyPath
。
  1. 更新
    DebugUtilities
    方法以采取可选
    PropertyPath
    :
    public static class DebugUtilities{ private Static 只读 ObjectVisitor s_Visitor = 新建(); public static void PrintObjectDump<T>(T value, PropertyPath path = default) { s_Visitor.Reset(); if (path.IsEmpty) PropertyContainer.Accept(s_Visitor, ref value); else PropertyContainer.Accept(s_Visitor, ref value, path); Debug.Log(s_Visitor.GetDump()); }}
  2. 使用
    Data
    Object 调用
    PrintObjectDump
    方法。控制台输出在如下所示:
    - Name { string} = Henry- Vec2 二维向量 = (1.00, 1.00)- 颜色<Color> - [0] = {颜色} RGBA(0.000, 1.000, 0.000, 1.000) - [1] = {颜色} RGBA(1.000, 0.000, 0.000, 1.000)- Dict {Dictionary<int, string> - [5] {KeyValuePair<int, string>} - Key {int} = 5 - 值 { string} = 五个

完整的访客代码

访问者类的完整代码现在如下所示:
using System.Text; using Unity.Properties; using UnityEngine; public class ObjectVisitor PropertyVisitor , IVisitPropertyAdapter<Vector2> , IVisitPropertyAdapter<Color> { private const int k_InitialIndent = 0; // StringBuilder to store the dumped object's properties and values. private 只读 StringBuilder m_构建器 = 新建 StringBuilder(); private 整型 m_IndentLevel = k_InitialIndent; // Helper property to get the current indentation. private 字符串 Indent => 新建(' ', m_IndentLevel * 2); public ObjectVisitor() { // Constructor, it initializes the ObjectVisitor and adds itself as an adapter // to handle properties of type Vector2 and Color. AddAdapter(this); } // Reset the visitor, clearing the StringBuilder and setting indentation to initial level. public void Reset() { m_Builder.Clear(); m_IndentLevel = k_InitialIndent; } // Get the string representation of the dumped object. public string GetDump() { return m_Builder.ToString(); } // Helper method to get the property name, handling collections and other property types. private Static 字符串 GetPropertyName(IProperty 属性) { return property switch { // If it's a collection element property, display it with brackets ICollectionElementProperty => $"[{property.Name}]", // For other property types, display the name as it is _ => property.Name }; } // This method is called when visiting each property of an object. // It determines the type of the value and formats it accordingly for display. protected override void VisitProperty<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value) { var propertyName = GetPropertyName(property); // Get the type of the value or property. var type = value?.GetType() ?? property.DeclaredValueType(); var typeName = TypeUtility.GetTypeDisplayName(type); // Only display the values for primitives, enums, and strings, and treat other types as containers. if (TypeTraits.IsContainer(type)) m_Builder.AppendLine($"{Indent}- {propertyName} {{{typeName}}}"); else m_Builder.AppendLine($"{Indent}- {propertyName} = {{{typeName}}} {value}"); // Increase indentation level before visiting child properties (if any). ++m_IndentLevel; if (null != value) PropertyContainer.Accept(this, ref value); // Decrease indentation level after visiting child properties. --m_IndentLevel; } // This method is a specialized override for Vector2 properties. // It displays the property name and its value as a Vector2. void IVisitPropertyAdapter<Vector2>.Visit<TContainer>(in VisitContext<TContainer, Vector2> context, ref TContainer container, ref Vector2 value) { var propertyName = GetPropertyName(context.Property); m_Builder.AppendLine($"{Indent}- {propertyName} = {{{nameof(Vector2)}}} {value}"); } // This method is a specialized override for Color properties. // It displays the property name and its value as a Color. void IVisitPropertyAdapter<Color>.Visit<TContainer>(in VisitContext<TContainer, Color> context, ref TContainer container, ref Color value) { var propertyName = GetPropertyName(context.Property); m_Builder.AppendLine($"{Indent}- {propertyName} = {{{nameof(Color)}}} {value}"); } }

其他资源