기술 자료

Unity 엔진

Unity 엔진

PropertyVisitor 클래스를 사용하여 프로퍼티 방문자 생성

PropertyVisitor 기본 클래스를 사용하여 예시에서 프로퍼티 방문자를 생성하는 방법을 알아봅니다.
읽는 시간 9분최근 업데이트: 9일 전

이 예제는
PropertyVisitor
기본 클래스를 사용하여 프로퍼티 방문자를 만드는 방법을 보여줍니다.
IPropertyBagVisitor
및
IPropertyVisitor
인터페이스를 사용하는 동등한 예제는 로우 레벨 API를 사용하여 프로퍼티 방문자 생성을 참고하십시오.

데이터 및 유틸리티 클래스 생성

간단한 데이터 클래스와 유틸리티 클래스를 생성하여 방문자가 해당 프로퍼티를 방문하고 출력하는 데 사용합니다.
  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
    라는 다음 유틸리티 클래스를 만듭니다.
    using UnityEngine;public static class DebugUtilities{ public static void PrintObjectDump<T>(T value) { // Magic goes here. }}

방문자 생성

다음과 같이 Visitor 클래스를 생성합니다.
  1. PropertyVisitor
    에서 상속하는
    ObjectVisitor
    라는 클래스를 만듭니다.
  2. 클래스에
    StringBuilder
    필드를 추가합니다. 오브젝트의 현재 상태를 나타내는 문자열을 빌드하는 데 사용할 수 있습니다.
  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 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(); }}

최상위 프로퍼티 가져오기

ObjectVisitor
클래스 내에서
VisitProperty
메서드를 오버라이드하여 오브젝트의 각 프로퍼티를 방문하고 프로퍼티 이름을 기록합니다.
PropertyVisitor
에는 구성원이 구현할 필요가 없으며 기본적으로 모든 등록 정보를 방문하고 작업을 수행하지 않습니다.
  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. 이제 방문자가 거의 없으므로 유틸리티 메서드를 구현할 수 있습니다.
    DebugUtilities
    클래스의
    PrintObjectDump
    메서드를 업데이트하여 새
    ObjectVisitor
    인스턴스를 생성하고 이를 사용하여 주어진 객체의 속성을 탐색합니다.
    public 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()); }}
  3. 코드의 적절한 위치에서
    PrintObjectDump
    메서드를 호출하고
    Data
    객체를 전달합니다. 예를 들어, 간단한 MonoBehaviour 구성 요소에서 이것은 다음과 같이 보일 수 있습니다.
    using UnityEngine;public class MyMonoBehaviour : MonoBehaviour{ void Start() { DebugUtilities.PrintObjectDump(new Data()); }}
    그러면 다음 출력이 콘솔에 출력됩니다.
    "name":- Vec2- 컬러- 딕트

하위 프로퍼티 가져오기

이전 섹션의 출력에 따르면,
VisitProperty
메서드를 오버라이드할 때 오브젝트의 하위 프로퍼티를 자동으로 방문하지 않습니다. 하위 프로퍼티를 가져오려면
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":- Vec2- x- y- 컬러- 0 - r - g - b - a- 1 - r - g - b - a - 딕트- 5 Key "value": "",

각 프로퍼티에 대한 추가 정보 표시

출력한 결과물을 더 개선하려면 컬렉션 항목의 프로퍼티 이름과 각 프로퍼티의 타입 및 값을 가져옵니다. 특정 프로퍼티에는 특히 컬렉션 아이템을 처리할 때 특수한 이름이 있습니다. 프로퍼티 이름에 대한 규칙은 다음과 같습니다.
  • 리스트 항목의 경우 이름은 인덱스에 해당합니다.
  • 딕셔너리의 경우 이름은 키 값의 문자열 버전에서 파생됩니다.
  • 세트의 경우 이름은 값의 문자열 버전에 기반합니다.
이 구별을 더 명시적으로 만들려면 프로퍼티 이름을 대괄호로 묶습니다.
  1. ObjectVisitor
    클래스 내에 다음 메서드를 추가합니다.
    private 정적 문자열 GetPropertyName(IProperty 프로퍼티){ return property switch { 별도로 // You can also treat `IListElementProperty`, `IDictionaryElementProperty`, `ISetElementProperty` ICollectionElementProperty => $"[{property.Name}]", _ => property.Name };}
  2. TypeUtility.GetTypeDisplayName
    를 사용하여 주어진 타입의 표시 이름을 가져오도록
    VisitProperty
    메서드를 업데이트합니다.
    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;}
    콘솔 출력은 다음과 같습니다.
    - 이름 = {문자열}- 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.IsContainer
유틸리티 메서드를 사용하여 프리미티브, 열거형, 문자열과 같이 하위 프로퍼티가 포함되지 않는 타입에 대한 값만 표시하도록
VisitProperty
를 업데이트하십시오.
ObjectVisitor
클래스에서
TypeTraits.IsContainer
를 사용하여 값이 컨테이너 타입인지 확인하도록
VisitProperty
메서드를 업데이트합니다. 이 경우 값 없이 타입 이름을 표시합니다. 그렇지 않으면 유형 이름과 값을 표시합니다.
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;}
콘솔 출력은 다음과 같습니다.
- 이름 = {문자열}- 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개
팁
표시되는 정보의 양을 줄이기 위해 다음 메서드를 사용하여 컬렉션 유형의
Visit
전문화를 오버라이드할 수도 있습니다.
이들은
VisitProperty
방법과 유사하지만 각각의 Collections 유형의 일반 파라미터를 노출합니다.

타입별 오버라이드 추가

타입별 오버라이드를 추가하여 더 컴팩트한 방식으로
Vector2
및
Color
타입을 표시합니다.
IVisitPropertyAdapter
와 함께
PropertyVisitor
를 사용하십시오. 어댑터가 특정 타입에 대해 등록되면, 방문 중에 타겟 타입이 발생하면, 어댑터가
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}"); }}

하위 프로퍼티에 대한 방문 시작

기본적으로 데이터에서 방문자를 실행하면 최상위 오브젝트에서 방문을 시작합니다. 모든 등록 정보 방문자의 경우 오브젝트의 하위 등록 정보에 대한 방문을 시작하려면
PropertyContainer.Accept
메서드에
PropertyPath
를 전달합니다.
  1. DebugUtilities
    메서드를 업데이트하여 선택적
    PropertyPath
    사용:
    public 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()); }}
  2. 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}"); } }

추가 리소스