PropertyVisitor 클래스를 사용하여 프로퍼티 방문자 생성
PropertyVisitor 기본 클래스를 사용하여 예시에서 프로퍼티 방문자를 생성하는 방법을 알아봅니다.
읽는 시간 9분최근 업데이트: 9일 전
이 예제는 기본 클래스를 사용하여 프로퍼티 방문자를 만드는 방법을 보여줍니다. 및 인터페이스를 사용하는 동등한 예제는 로우 레벨 API를 사용하여 프로퍼티 방문자 생성을 참고하십시오.
PropertyVisitorIPropertyBagVisitorIPropertyVisitor데이터 및 유틸리티 클래스 생성
간단한 데이터 클래스와 유틸리티 클래스를 생성하여 방문자가 해당 프로퍼티를 방문하고 출력하는 데 사용합니다.
-
액세스 가능한 프로퍼티가 있는라는 다음 C# 클래스를 생성합니다.
Datausing 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" } };} -
라는 다음 유틸리티 클래스를 만듭니다.
DebugUtilitiesusing UnityEngine;public static class DebugUtilities{ public static void PrintObjectDump<T>(T value) { // Magic goes here. }}
방문자 생성
다음과 같이 Visitor 클래스를 생성합니다.
-
에서 상속하는
PropertyVisitor라는 클래스를 만듭니다.ObjectVisitor -
클래스에필드를 추가합니다. 오브젝트의 현재 상태를 나타내는 문자열을 빌드하는 데 사용할 수 있습니다.
StringBuilder -
를 지우고 들여쓰기 레벨을 재설정하는
StringBuilder메서드를 추가합니다.Reset -
오브젝트의 현재 상태를 나타내는 문자열을 반환하는메서드를 추가합니다.
GetDump이제클래스가 다음과 같이 표시됩니다.ObjectVisitor// `PropertyVisitor` is an abstract class that you must derive from. public class ObjectVisitor: PropertyVisitor{ private const int k_InitialIndent = 0; private readonly StringBuilder m_Builder = new StringBuilder(); private int m_IndentLevel = k_InitialIndent; private 문자열 Indent => new (', m_IndentLevel * 2); public void Reset() { m_Builder.Clear(); m_IndentLevel = k_InitialIndent; } public string GetDump() { return m_Builder.ToString(); }}
최상위 프로퍼티 가져오기
ObjectVisitorVisitPropertyPropertyVisitor-
클래스 내에 다음 오버라이드
ObjectVisitor메서드를 추가합니다.VisitPropertyprotected override void VisitProperty<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container, ref TValue value){ m_Builder.AppendLine($"- {property.Name}");} -
이제 방문자가 거의 없으므로 유틸리티 메서드를 구현할 수 있습니다.클래스의
DebugUtilities메서드를 업데이트하여 새PrintObjectDump인스턴스를 생성하고 이를 사용하여 주어진 객체의 속성을 탐색합니다.ObjectVisitorpublic static class DebugUtilities{ private static readonly ObjectVisitor s_Visitor = new(); 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()); }} -
코드의 적절한 위치에서메서드를 호출하고
PrintObjectDump객체를 전달합니다. 예를 들어, 간단한 MonoBehaviour 구성 요소에서 이것은 다음과 같이 보일 수 있습니다.Datausing UnityEngine;public class MyMonoBehaviour : MonoBehaviour{ void Start() { DebugUtilities.PrintObjectDump(new Data()); }}그러면 다음 출력이 콘솔에 출력됩니다."name":- Vec2- 컬러- 딕트
하위 프로퍼티 가져오기
이전 섹션의 출력에 따르면, 메서드를 오버라이드할 때 오브젝트의 하위 프로퍼티를 자동으로 방문하지 않습니다. 하위 프로퍼티를 가져오려면 메서드를 사용하여 각 값에 방문자를 재귀적으로 적용합니다.
VisitPropertyPropertyContainer.AcceptObjectVisitorVisitPropertyprotected 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":- Vec2- x- y- 컬러- 0 - r - g - b - a- 1 - r - g - b - a - 딕트- 5 Key "value": "",
각 프로퍼티에 대한 추가 정보 표시
출력한 결과물을 더 개선하려면 컬렉션 항목의 프로퍼티 이름과 각 프로퍼티의 타입 및 값을 가져옵니다. 특정 프로퍼티에는 특히 컬렉션 아이템을 처리할 때 특수한 이름이 있습니다. 프로퍼티 이름에 대한 규칙은 다음과 같습니다.
- 리스트 항목의 경우 이름은 인덱스에 해당합니다.
- 딕셔너리의 경우 이름은 키 값의 문자열 버전에서 파생됩니다.
- 세트의 경우 이름은 값의 문자열 버전에 기반합니다.
이 구별을 더 명시적으로 만들려면 프로퍼티 이름을 대괄호로 묶습니다.
-
클래스 내에 다음 메서드를 추가합니다.
ObjectVisitorprivate 정적 문자열 GetPropertyName(IProperty 프로퍼티){ return property switch { 별도로 // You can also treat `IListElementProperty`, `IDictionaryElementProperty`, `ISetElementProperty` ICollectionElementProperty => $"[{property.Name}]", _ => property.Name };} -
를 사용하여 주어진 타입의 표시 이름을 가져오도록
TypeUtility.GetTypeDisplayName메서드를 업데이트합니다.VisitPropertyprotected 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;}콘솔 출력은 다음과 같습니다.- 이름 = {문자열}- Vec2 = {Vector2} (1.00, 1.00)- x = {float} 1- y = {float} 1- Colors = {List<Color>} System.Collections.Generic.List`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.String]- [5] = {KeyValuePair<int, string>} [5, five] - 키 = {int} 5 - 값 = {문자열} 5개
컬렉션 유형에 대한 적은 정보 표시
List<T>ToString()System.Collections.Generic.List1[UnityEngine.Color]TypeTraits.IsContainerVisitPropertyObjectVisitorTypeTraits.IsContainerVisitPropertyprotected 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;}
콘솔 출력은 다음과 같습니다.
- 이름 = {문자열}- Vec2 {Vector2}- x = {float} 1- y = {float} 1- 컬러 {List<Color>}- [0] {Color} - r = {float} 0 - g = {float} 1 - b = {float} 0 - a = {float} 1- [1] {Color} - r = {float} 1 - g = {float} 0 - b = {float} 0 - a = {float} 1- 딕셔너리 {Dictionary<int, string>}- [5] {KeyValuePair<int, string>} - 키 = {int} 5 - 값 = {문자열} 5개
PropertyVisitor.VisitCollectionPropertyVisitor.VisitListPropertyVisitor.VisitDictionaryPropertyVisitor.VisitSet
이들은 방법과 유사하지만 각각의 Collections 유형의 일반 파라미터를 노출합니다.
VisitProperty타입별 오버라이드 추가
IVisitPropertyAdapterPropertyVisitorVisitPropertyObjectVisitorVector2ColorIVisitPropertyAdapterpublic 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}"); }}
하위 프로퍼티에 대한 방문 시작
기본적으로 데이터에서 방문자를 실행하면 최상위 오브젝트에서 방문을 시작합니다. 모든 등록 정보 방문자의 경우 오브젝트의 하위 등록 정보에 대한 방문을 시작하려면 메서드에 를 전달합니다.
PropertyContainer.AcceptPropertyPath-
메서드를 업데이트하여 선택적
DebugUtilities사용:PropertyPathpublic static class DebugUtilities{ private static readonly ObjectVisitor s_Visitor = new(); 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()); }} -
객체로
Data메서드를 호출합니다. 콘솔 출력은 다음과 같습니다.PrintObjectDump- 이름 {string} = Henry- Vec2 {Vector2} = (1.00, 1.00)- 컬러 {List<Color>} - [0] = {Color} RGBA(0.000, 1.000, 0.000, 1.000) - [1] = {Color} RGBA(1.000, 0.000, 0.000, 1.000)- 딕셔너리 {Dictionary<int, string>} - [5] {KeyValuePair<int, string>} - 키 {int} = 5 - 값 {문자열} = 5
방문자 코드 완성
이제 Visitor 클래스에 대한 전체 코드가 다음과 같이 표시됩니다.
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 readonly StringBuilder m_Builder = new StringBuilder(); private int m_IndentLevel = k_InitialIndent; // Helper property to get the current indentation. private string Indent => new(' ', 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 정적 문자열 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}"); } }