기술 자료

Unity 엔진

Unity 엔진

저수준 API로 프로퍼티 방문자 생성

예시에서 IPropertyBagVisitor 및 IPropertyVisitor 인터페이스를 사용하여 프로퍼티 방문자를 만드는 방법을 알아봅니다.
읽는 시간 7분최근 업데이트: 9일 전

이 예제는 저수준
IPropertyBagVisitor
및
IPropertyVisitor
인터페이스를 사용하여 프로퍼티 방문자를 만드는 방법을 보여줍니다. PropertyVisitor 클래스 예시로 프로퍼티를 생성하는 방문자와 동일한 결과를 얻지만, 에서 파생된 방문자가 아니라 이러한 인터페이스를 구현하는 방문자입니다
PropertyVisitor
.

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

  1. PropertyVisitor 클래스 예시를 사용하여 Create a property visitor에서와 동일한
    Data
    클래스와
    DebugUtilities
    클래스를 생성합니다.
  2. 다음과 같이
    PropertyVisitor
    파생 방문자 대신 저수준 방문자를 사용하도록
    DebugUtilities
    클래스를 수정합니다.
    public static class DebugUtilities{ private static readonly LowLevelVisitor 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()); }}

방문자 생성

다음과 같이 저수준 방문자 클래스를 생성합니다.
  1. IPropertyVisitor
    및
    IPropertyBagVisitor
    인터페이스를 구현하는
    LowLevelVisitor
    클래스를 생성합니다.
  2. 클래스에
    StringBuilder
    필드를 추가합니다. 오브젝트의 현재 상태를 나타내는 문자열을 빌드하는 데 사용할 수 있습니다.
  3. StringBuilder
    를 지우고 들여쓰기 레벨을 재설정하는
    Reset
    메서드를 추가합니다.
  4. 오브젝트의 현재 상태를 나타내는 문자열을 반환하는
    GetDump
    메서드를 추가합니다.
    이제
    LowLevelVisitor
    클래스가 다음과 같이 표시됩니다.
    public class LowLevelVisitor : IPropertyBagVisitor , IPropertyVisitor{ private const int k_InitialIndent = 0; private readonly StringBuilder m_Builder = new StringBuilder(); private int m_IndentLevel = k_InitialIndent; public void Reset() { m_Builder.Clear(); m_IndentLevel = k_InitialIndent; } public string GetDump() { return m_Builder.ToString(); }}

프로퍼티 가져오기

this
를 사용하여 프로퍼티의
Accept
메서드를 호출하려면
IPropertyVisitor
인터페이스를 구현합니다. 이 인터페이스를 사용하면
PropertyVisitorVisitProperty
방법과 유사하게 속성을 방문할 때 방문 동작을 지정할 수 있습니다.
  1. LowLevelVisitor
    클래스에서 다음과 같이
    IPropertyBagVisitor.Visit
    및
    IPropertyVisitor.Visit
    메서드를 오버라이드합니다.
    void IPropertyBagVisitor.Visit<TContainer>(IPropertyBag<TContainer> propertyBag, ref TContainer container){ Foreach (propertyBag.GetProperties(ref container)의 var 속성) { property.Accept(this, ref container); }} void IPropertyVisitor.Visit<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container){ var value = property.GetValue(ref container); // Code goes here.}
  2. PropertyVisitor
    기본 클래스와 함께 사용되는
    IVisitPropertyAdapter
    어댑터는 방문자의 내부 상태에 액세스해야 하므로 해당 클래스 외부에서 사용할 수 없습니다. 하지만 필요한 정보가 포함된 도메인별 어댑터를 정의할 수 있습니다.
    LowLevelVisitor
    클래스와 동일한 파일에서 이러한 어댑터의
    IPrintValue
    및
    IPrintValue<in T>
    인터페이스와 어댑터가 프로퍼티 값을 포맷하는 데 필요한 정보를 캡슐화하는
    PrintContext
    구조체를 다음과 같이 정의합니다.
    // Create the following struct with methods to encapsulate the formatting of the message and display the value.public readonly struct PrintContext{ private StringBuilder 빌더 { get; } private 문자열 접두어 { get; } public string PropertyName { get; } public void Print<T>(T value) { Builder.AppendLine($"{Prefix}- {PropertyName} = {{{TypeUtility.GetTypeDisplayName(value?.GetType() ?? typeof(T))}}} {value}"); } public void Print(Type type, string value) { Builder.AppendLine($"{Prefix}- {PropertyName} = {{{TypeUtility.GetTypeDisplayName(type)}}} {value}"); } public PrintContext(StringBuilder builder, string prefix, string propertyName) { Builder = builder; Prefix = prefix; PropertyName = propertyName; }}public interface IPrintValue{}public interface IPrintValue<in T> : IPrintValue{ void PrintValue(in PrintContext context, T value);}
  3. LowLevelVisitor
    클래스에서 어댑터 인터페이스 메서드를 오버라이드하여
    Vector2
    및
    Color
    에 대한 타입별 어댑터를 생성하고 먼저 어댑터를 사용하도록
    IPropertyVisitor
    의 구현을 업데이트합니다.
    public class LowLevelVisitor : IPropertyBagVisitor , IPropertyVisitor , IPrintValue<Vector2> , IPrintValue<Color>{ public IPrintValue Adapter { get; set; } public LowLevelVisitor() { // For simplicity Adapter = this; } void IPropertyVisitor.Visit<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container) { // Here, we need to manually extract the value. var value = property.GetValue(ref container); var propertyName = GetPropertyName(property); // We can still use adapters, but we must manually dispatch the calls. if (Adapter is IPrintValue<TValue> adapter) { var context = new PrintContext(m_Builder, Indent, propertyName); adapter.PrintValue(context, value); 반환; } // Fallback behaviour here } void IPrintValue<Vector2>.PrintValue(in PrintContext context, Vector2 value) { context.Print(value); } void IPrintValue<Color>.PrintValue(in PrintContext context, Color value) { const 문자열 포맷 = "F3"; var formatProvider = CultureInfo.InvariantCulture.NumberFormat; context.Print(typeof(Color), $"RGBA({value.r.ToString(format, formatProvider)}, {value.g.ToString(format, formatProvider)}, {value.b.ToString(format, formatProvider)}, {value.a.ToString(format, formatProvider)})"); }}

방문자 코드 완성

저수준 방문자 클래스와
Color
및
Vector2
커스텀 어댑터의 전체 코드는 다음과 같습니다.
using UnityEngine; using System.Globalization; using System.Text; using Unity.Properties; public readonly struct PrintContext { // A context struct to hold information about how to print the property. private StringBuilder 빌더 { get; } private 문자열 접두어 { get; } public string PropertyName { get; } // Method to print the value of type T with its associated property name. public void Print<T>(T value) { Builder.AppendLine($"{Prefix}- {PropertyName} = {{{TypeUtility.GetTypeDisplayName(value?.GetType() ?? typeof(T))}}} {value}"); } // Method to print the value with a specified type and its associated property name. public void Print(System.Type type, string value) { Builder.AppendLine($"{Prefix}- {PropertyName} = {{{TypeUtility.GetTypeDisplayName(type)}}} {value}"); } // Constructor to initialize the PrintContext. public PrintContext(StringBuilder builder, string prefix, string propertyName) { Builder = builder; Prefix = prefix; PropertyName = propertyName; } } // Generic interface IPrintValue that acts as a marker interface for all print value adapters. public interface IPrintValue { } // Generic interface IPrintValue<T> to define how to print values of type T. // This interface is used as an adapter for specific types (Vector2 and Color in this case). public interface IPrintValue<in T> : IPrintValue { void PrintValue(in PrintContext context, T value); } // LowLevelVisitor class that implements various interfaces for property visiting and value printing. public class LowLevelVisitor : IPropertyBagVisitor, IPropertyVisitor, IPrintValue<Vector2>, IPrintValue<Color> { private const int k_InitialIndent = 0; private readonly StringBuilder m_Builder = new StringBuilder(); private int m_IndentLevel = k_InitialIndent; public IPrintValue Adapter { get; set; } public LowLevelVisitor() { // The Adapter property is set to this instance of LowLevelVisitor. // This means the current LowLevelVisitor can be used as a print value adapter for Vector2 and Color. Adapter = 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 a property bag (a collection of properties) void IPropertyBagVisitor.Visit<TContainer>(IPropertyBag<TContainer> propertyBag, ref TContainer container) { Foreach (propertyBag.GetProperties(ref container)의 var 속성) { // Call the Visit method of IPropertyVisitor to handle individual properties. property.Accept(this, ref container); } } // This method is called when visiting each individual property of an object. // It tries to find a suitable adapter (IPrintValue<T>) for the property value type (TValue) and uses it to print the value. // If no suitable adapter is found, it falls back to displaying the value using its type name. void IPropertyVisitor.Visit<TContainer, TValue>(Property<TContainer, TValue> property, ref TContainer container) { // Here, we need to manually extract the value. var value = property.GetValue(ref container); var propertyName = GetPropertyName(property); // We can still use adapters, but we must manually dispatch the calls. // Try to find an adapter for the current property value type (TValue). if (Adapter is IPrintValue<TValue> adapter) { // If an adapter is found, create a print context and call the PrintValue method of the adapter. var context = new PrintContext(m_Builder, m_IndentLevel.ToString(), propertyName); adapter.PrintValue(context, value); 반환; } // Fallback behavior here - if no adapter is found, handle printing based on type information. var type = value?.GetType() ?? property.DeclaredValueType(); var typeName = TypeUtility.GetTypeDisplayName(type); if (TypeTraits.IsContainer(type)) m_Builder.AppendLine($"{m_IndentLevel}- {propertyName} {{{typeName}}}"); else m_Builder.AppendLine($"{m_IndentLevel}- {propertyName} = {{{typeName}}} {value}"); // Recursively visit child properties (if any). ++m_IndentLevel; if (null != value) PropertyContainer.Accept(this, ref value); --m_IndentLevel; } // Method from IPrintValue<Vector2> used to print Vector2 values. void IPrintValue<Vector2>.PrintValue(in PrintContext context, Vector2 value) { // Simply use the Print method of PrintContext to print the Vector2 value. context.Print(value); } // Method from IPrintValue<Color> used to print Color values. void IPrintValue<Color>.PrintValue(in PrintContext context, Color value) { const 문자열 포맷 = "F3"; var formatProvider = CultureInfo.InvariantCulture.NumberFormat; // Format and print the Color value in RGBA format. context.Print(typeof(Color), $"RGBA({value.r.ToString(format, formatProvider)}, {value.g.ToString(format, formatProvider)}, {value.b.ToString(format, formatProvider)}, {value.a.ToString(format, formatProvider)})"); } }
LowLevelVisitor.cs
파일에 이 코드의 완전한 버전이 있으면
Data
클래스의 인스턴스가 있는
DebugUtilities.PrintObjectDump
메서드를 호출하여 PropertyVisitor 클래스 예시를 사용하여 Create a property visitor의 최종 단계에서와 동일한 콘솔 출력을 생성하는지 확인합니다.
using UnityEngine;public class MyMonoBehaviour : MonoBehaviour{ void Start() { DebugUtilities.PrintObjectDump(new Data()); }}

추가 리소스