Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-opus-4-20250514· AnthropicHugging Face LMArena Human Preference 140K

unity , c# , vcontainer , message pipe , 특정 변수가 값이 변화가 있을때 알려주는 기능

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with grok-3-mini-beta’s answer.
  1. User

    unity , c# , vcontainer , message pipe ,

    특정 변수가 값이 변화가 있을때 알려주는 기능

  2. Claude Assistant

    Unity에서 VContainer와 MessagePipe를 사용하여 변수 값 변화를 감지하고 알림을 받는 기능을 구현하는 방법을 설명드리겠습니다.

    1. 기본 구조 설정

    먼저 MessagePipe를 사용한 이벤트 발행/구독 시스템을 구현합니다:

    using MessagePipe;
    using VContainer;
    using VContainer.Unity;
    using System;
    using UniRx;
    
    // 값 변경 이벤트 메시지
    public struct ValueChangedMessage<T>
    {
        public T OldValue { get; }
        public T NewValue { get; }
        public string PropertyName { get; }
        
        public ValueChangedMessage(T oldValue, T newValue, string propertyName)
        {
            OldValue = oldValue;
            NewValue = newValue;
            PropertyName = propertyName;
        }
    }
    

    2. Observable Property 구현

    값 변화를 감지하는 프로퍼티 래퍼를 만듭니다:

    public class ObservableProperty<T>
    {
        private T _value;
        private readonly IPublisher<ValueChangedMessage<T>> _publisher;
        private readonly string _propertyName;
        
        public T Value
        {
            get => _value;
            set
            {
                if (!Equals(_value, value))
                {
                    var oldValue = _value;
                    _value = value;
                    _publisher.Publish(new ValueChangedMessage<T>(oldValue, value, _propertyName));
                }
            }
        }
        
        public ObservableProperty(IPublisher<ValueChangedMessage<T>> publisher, string propertyName, T initialValue = default)
        {
            _publisher = publisher;
            _propertyName = propertyName;
            _value = initialValue;
        }
    }
    

    3. VContainer 설정

    DI 컨테이너 설정을 구성합니다:

    public class GameLifetimeScope : LifetimeScope
    {
        protected override void Configure(IContainerBuilder builder)
        {
            // MessagePipe 설정
            var options = builder.RegisterMessagePipe();
            
            // 특정 타입별 Publisher/Subscriber 등록
            builder.RegisterMessageBroker<ValueChangedMessage<int>>(options);
            builder.RegisterMessageBroker<ValueChangedMessage<float>>(options);
            builder.RegisterMessageBroker<ValueChangedMessage<string>>(options);
            
            // 서비스 등록
            builder.Register<PlayerDataService>(Lifetime.Singleton);
            builder.RegisterEntryPoint<GamePresenter>();
        }
    }
    

    4. 실제 사용 예제

    플레이어 데이터 서비스에서 Observable 프로퍼티를 사용하는 예제:

    public class PlayerDataService
    {
        public ObservableProperty<int> Health { get; }
        public ObservableProperty<float> Score { get; }
        public ObservableProperty<string> PlayerName { get; }
        
        public PlayerDataService(
            IPublisher<ValueChangedMessage<int>> intPublisher,
            IPublisher<ValueChangedMessage<float>> floatPublisher,
            IPublisher<ValueChangedMessage<string>> stringPublisher)
        {
            Health = new ObservableProperty<int>(intPublisher, nameof(Health), 100);
            Score = new ObservableProperty<float>(floatPublisher, nameof(Score), 0f);
            PlayerName = new ObservableProperty<string>(stringPublisher, nameof(PlayerName), "Player");
        }
    }
    

    5. 구독자 구현

    값 변화를 구독하고 처리하는 Presenter:

    public class GamePresenter : IStartable, IDisposable
    {
        private readonly PlayerDataService _playerData;
        private readonly ISubscriber<ValueChangedMessage<int>> _intSubscriber;
        private readonly ISubscriber<ValueChangedMessage<float>> _floatSubscriber;
        private readonly CompositeDisposable _disposables = new();
        
        public GamePresenter(
            PlayerDataService playerData,
            ISubscriber<ValueChangedMessage<int>> intSubscriber,
            ISubscriber<ValueChangedMessage<float>> floatSubscriber)
        {
            _playerData = playerData;
            _intSubscriber = intSubscriber;
            _floatSubscriber = floatSubscriber;
        }
        
        public void Start()
        {
            // Health 변화 구독
            _intSubscriber
                .Subscribe(msg =>
                {
                    if (msg.PropertyName == nameof(PlayerDataService.Health))
                    {
                        Debug.Log($"Health changed: {msg.OldValue} -> {msg.NewValue}");
                        UpdateHealthUI(msg.NewValue);
                    }
                })
                .AddTo(_disposables);
                
            // Score 변화 구독
            _floatSubscriber
                .Subscribe(msg =>
                {
                    if (msg.PropertyName == nameof(PlayerDataService.Score))
                    {
                        Debug.Log($"Score changed: {msg.OldValue} -> {msg.NewValue}");
                        UpdateScoreUI(msg.NewValue);
                    }
                })
                .AddTo(_disposables);
        }
        
        private void UpdateHealthUI(int health) { /* UI 업데이트 로직 */ }
        private void UpdateScoreUI(float score) { /* UI 업데이트 로직 */ }
        
        public void Dispose()
        {
            _disposables.Dispose();
        }
    }
    

    6. 더 간단한 방법 - ReactiveProperty 사용

    UniRx의 ReactiveProperty를 MessagePipe와 함께 사용하는 방법:

    public class PlayerDataWithReactive
    {
        public ReactiveProperty<int> Health { get; } = new(100);
        public ReactiveProperty<float> Score { get; } = new(0f);
        
        private readonly IPublisher<ValueChangedMessage<object>> _publisher;
        
        public PlayerDataWithReactive(IPublisher<ValueChangedMessage<object>> publisher)
        {
            _publisher = publisher;
            
            // ReactiveProperty 변화를 MessagePipe로 전달
            Health.Subscribe(value => 
                _publisher.Publish(new ValueChangedMessage<object>(null, value, nameof(Health))));
                
            Score.Subscribe(value => 
                _publisher.Publish(new ValueChangedMessage<object>(null, value, nameof(Score))));
        }
    }
    

    이러한 구조를 사용하면 변수 값의 변화를 효과적으로 감지하고, 관심 있는 컴포넌트들에게 알림을 보낼 수 있습니다. MessagePipe의 pub/sub 패턴과 VContainer의 DI를 활용하여 느슨하게 결합된 시스템을 구축할 수 있습니다.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.