PlayerData 를 ScriptableObject 로 만들고 , Health 변수를 넣고 , Health 변화에 따라 UI 출력이 되도록 ,…
- User
PlayerData 를 ScriptableObject 로 만들고 , Health 변수를 넣고 , Health 변화에 따라 UI 출력이 되도록 , VContainer 와 ReactiveProperty , 필요하면 MessagePipe 까지 활용해서 보여줘
Assistant
Unity에서
ScriptableObject를 사용하여 플레이어 데이터를 관리하고,ReactiveProperty로 값 변화를 감지하며,VContainer를 통해 의존성 주입을 적용하는 예제를 아래에 설명합니다.MessagePipe도 필요에 따라 추가할 수 있도록 구조를 설계하겠습니다.
1. PlayerData ScriptableObject 생성
1.1. PlayerData.cs (ScriptableObject)
플레이어 데이터를 저장하는
ScriptableObject로,Health변수를ReactiveProperty로 정의합니다.using UnityEngine; using Reactive.Bindings; [CreateAssetMenu(fileName = "NewPlayerData", menuName = "ScriptableObjects/PlayerData")] public class PlayerData : ScriptableObject { // Health 값 변경 알림을 위한 ReactiveProperty public ReactiveProperty<int> Health { get; } = new ReactiveProperty<int>(100); }
2. VContainer 설정
2.1. GameLifetimeScope.cs (DI 컨테이너 설정)
PlayerDataScriptableObject를 VContainer에 등록합니다. 이는 Inspector에서 특정 ScriptableObject 인스턴스를 할당해야 합니다.using UnityEngine; using VContainer; using VContainer.Unity; public class GameLifetimeScope : LifetimeScope { [SerializeField] private PlayerData playerData; // Inspector에서 할당 [SerializeField] private HealthDisplay healthDisplay; // UI 컴포넌트 할당 protected override void Configure(IContainerBuilder builder) { // ScriptableObject 인스턴스 등록 builder.RegisterInstance(playerData); // HealthDisplay 등록 builder.RegisterInstance(healthDisplay); // EntryPoint 등록 (선택 사항) builder.RegisterEntryPoint<GamePresenter>(); } }
3. UI 업데이트 컴포넌트 (HealthDisplay)
3.1. HealthDisplay.cs (UI 업데이트)
PlayerData를 의존성 주입으로 받아 Health 값 변화를 감지하고 UI를 업데이트합니다.using UnityEngine; using UnityEngine.UI; using Reactive.Bindings; using System.Reactive.Linq; using VContainer.Unity; public class HealthDisplay : MonoBehaviour { [SerializeField] private Text healthText; private PlayerData _playerData; private readonly CompositeDisposable _disposables = new(); [Inject] public void InjectDependencies(PlayerData playerData) { _playerData = playerData; } private void OnEnable() { // Health 값 변화에 대한 구독 _playerData.Health .ObserveOn(UnityMainThreadDispatcher.Instance) // 메인 스레드 보장 .Subscribe(health => { healthText.text = $"Health: {health}"; }) .AddTo(_disposables); } private void OnDisable() { _disposables.Dispose(); } }
4. MessagePipe 활용 (선택 사항)
4.1. PlayerData.cs (MessagePipe 추가)
MessagePipe를 사용하여 Health 변경 이벤트를 발행합니다.using UnityEngine; using Reactive.Bindings; using MessagePipe; [CreateAssetMenu(fileName = "NewPlayerData", menuName = "ScriptableObjects/PlayerData")] public class PlayerData : ScriptableObject { public ReactiveProperty<int> Health { get; } = new ReactiveProperty<int>(100); // MessagePipe Publisher private readonly IPublisher<HealthChangedEventArgs> _publisher; public PlayerData(IPublisher<HealthChangedEventArgs> publisher) { _publisher = publisher; } // Health 값 변경 시 이벤트 발행 public void SetHealth(int value) { var oldValue = Health.Value; Health.Value = value; _publisher.Publish(new HealthChangedEventArgs(oldValue, Health.Value)); } // HealthChangedEventArgs 메시지 정의 public struct HealthChangedEventArgs { public int OldValue { get; } public int NewValue { get; } public HealthChangedEventArgs(int oldValue, int newValue) { OldValue = oldValue; NewValue = newValue; } } }4.2. HealthDisplay.cs (MessagePipe 구독)
MessagePipe를 통해 Health 변경 이벤트를 받는 UI 컴포넌트.using UnityEngine; using UnityEngine.UI; using VContainer.Unity; using MessagePipe; public class HealthDisplay : MonoBehaviour { [SerializeField] private Text healthText; private readonly CompositeDisposable _disposables = new(); [Inject] public void InjectDependencies(ISubscriber<PlayerData.HealthChangedEventArgs> subscriber) { subscriber.Subscribe(eventArgs => { healthText.text = $"Health: {eventArgs.NewValue}"; }) .AddTo(_disposables); } private void OnDisable() { _disposables.Dispose(); } }
5. VContainer 설정 (MessagePipe 추가)
5.1. GameLifetimeScope.cs (MessagePipe 설정)
MessagePipe를 VContainer에 등록합니다.using VContainer; using VContainer.Unity; using MessagePipe; public class GameLifetimeScope : LifetimeScope { [SerializeField] private PlayerData playerData; [SerializeField] private HealthDisplay healthDisplay; protected override void Configure(IContainerBuilder builder) { // MessagePipe 설정 var options = builder.RegisterMessagePipe(); // HealthChangedEventArgs 메시지 브로커 등록 builder.RegisterMessageBroker<PlayerData.HealthChangedEventArgs>(options); // PlayerData 등록 (MessagePipe Publisher 주입) builder.Register<PlayerData>(Lifetime.Singleton) .WithParameter(typeof(IPublisher<PlayerData.HealthChangedEventArgs>), new MessagePipePublisher<PlayerData.HealthChangedEventArgs>()); // HealthDisplay 등록 builder.RegisterInstance(healthDisplay); builder.RegisterEntryPoint<GamePresenter>(); } }
6. 실행 흐름
-
PlayerData 초기화
ScriptableObject로 생성된PlayerData인스턴스가 VContainer에 등록됩니다.Health는ReactiveProperty로 초기화됩니다.
-
UI 연결
HealthDisplay는PlayerData를 의존성 주입으로 받아 Health 값 변화를 감지합니다.MessagePipe를 사용하는 경우, Health 변경 이벤트를 구독합니다.
-
Health 값 변경
PlayerData.SetHealth(90)를 호출하면:ReactiveProperty가 UI를 업데이트합니다.MessagePipe가 구독자들에게 이벤트를 발행합니다.
7. Scene 설정
-
GameObject 생성 및 설정
- GameLifetimeScope:
GameLifetimeScope컴포넌트 추가.- Inspector에서
PlayerData와HealthDisplay필드에 해당 인스턴스 할당.
- UI 요소:
Text컴포넌트를 가지는 GameObject에HealthDisplay컴포넌트 추가.
- GameLifetimeScope:
-
ScriptableObject 생성
Assets > Create > ScriptableObjects > PlayerData로 인스턴스 생성.
8. 결과
PlayerData의Health값이 변경되면,HealthDisplay의 텍스트가 실시간으로 업데이트됩니다.ReactiveProperty로 직접 구독하거나,MessagePipe를 통해 이벤트를 처리할 수 있습니다.- VContainer를 통해 모든 의존성이 명시적으로 관리됩니다.
9. 추가 고려사항
9.1. 메인 스레드 보장
ReactiveProperty의 이벤트는 Unity 메인 스레드에서 실행되도록 설정해야 합니다:Health = new ReactiveProperty<int>(100, raiseEventScheduler: UnityMainThreadScheduler.Instance);
9.2. 테스트
- ViewModel 테스트:
[Test] public void Health_ValueChanged_UpdatesUI() { var playerData = new PlayerData(); var healthDisplay = new HealthDisplay(); playerData.Health.Value = 80; Assert.AreEqual("Health: 80", healthDisplay.healthText.text); // 가정 }
9.3. MessagePipe vs ReactiveProperty
- ReactiveProperty는 직접적인 구독을 통해 간단히 구현 가능합니다.
- MessagePipe는 다른 컴포넌트나 시스템 간 통신에 유용합니다 (예: 네트워크 동기화).
이 구조를 통해 데이터, UI, DI, 이벤트 처리를 명확하게 분리하여 유지보수성과 확장성을 높일 수 있습니다.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.