ABOUT PORTFOLIO GAMES DEVLOG DOCS TOOLS CONTACT
HOME > DOCS > Unity / C# > ScriptableObject 기반 모듈형 게임 변수 및 이벤트 아키텍처Modular Game Variables and Event Architecture Using ScriptableObjects
Unity / C# Intermediate Unity 2021.3+ / Unity 6

ScriptableObject 기반 모듈형 게임 변수 및 이벤트 아키텍처Modular Game Variables and Event Architecture Using ScriptableObjects

싱글톤 없이 ScriptableObject를 데이터 컨테이너와 이벤트 브로커로 사용하여 씬 간 데이터 공유와 UI-게임플레이 디커플링을 달성하는 라이언 히플(Ryan Hipple) 아키텍처.An architecture pattern inspired by Ryan Hipple that uses ScriptableObjects as data containers and event brokers to share data across scenes and decouple UI from gameplay without singletons.

#Unity #ScriptableObject #Architecture #Design Pattern
핵심 개념게임 내 플레이어 체력이나 점수를 FloatVariable이라는 ScriptableObject 에셋 파일로 만들면, 씬에 플레이어가 스폰되지 않은 프리팹 상태나 UI에서도 인스펙터 드래그 앤 드롭만으로 변수를 관찰하고 연동할 수 있습니다.
Core ConceptRepresenting player health or score as a FloatVariable ScriptableObject asset allows UI components and prefabs to observe and bind to shared data via Inspector drag-and-drop, even when the player object has not yet spawned in the scene.

1. 모듈형 SO 변수 구현1. Modular SO Variable Implementation

FloatVariable.cs
using System;
using UnityEngine;

[CreateAssetMenu(menuName = "Variables/Float Variable")]
public class FloatVariable : ScriptableObject
{
    [SerializeField] private float value;
    public event Action<float> OnValueChanged;

    public float Value
    {
        get => value;
        set
        {
            this.value = value;
            OnValueChanged?.Invoke(this.value);
        }
    }
}

2. 실무 적용 및 주의사항2. Practical Considerations

  • 에디터 플레이 모드 값 잔류 주의: 에디터에서 플레이 도중 ScriptableObject의 직렬화된 필드를 변경하면 플레이 종료 후에도 변경된 값이 에셋에 그대로 남습니다. 직렬화된 초기값(InitialValue)과 비직렬화 런타임 값([NonSerialized] RuntimeValue)을 분리하는 것이 안전합니다.
  • 이벤트 구독 해제 필수: 에셋 파일은 씬 전환과 무관하게 메모리에 유지될 수 있으므로, OnValueChanged를 구독한 MonoBehaviour 컴포넌트는 OnDisable에서 반드시 구독을 해제(-=)해야 메모리 누수와 참조 오류를 방지할 수 있습니다.
  • 세이브 데이터와의 역할 구분: 빌드된 런타임 환경에서는 ScriptableObject의 값을 변경해도 디스크에 영구 저장되지 않으므로, 실제 게임 세이브 데이터는 별도의 JSON이나 파일 직렬화 시스템으로 관리해야 합니다.
  • Prevent Editor Play Mode Value Persistence: Modifying serialized fields on a ScriptableObject during Play Mode in the Editor persists those changes to the asset file after exiting Play Mode. Separate the serialized InitialValue from a [NonSerialized] runtime value to avoid unintended asset modifications.
  • Always Unsubscribe Events: Because ScriptableObject assets can remain loaded across scene transitions, any MonoBehaviour subscribing to OnValueChanged must unsubscribe (-=) in OnDisable to prevent memory leaks and missing reference errors.
  • Not a Replacement for Save Files: In standalone player builds, runtime changes to ScriptableObject fields are not written back to disk, so persistent save data must still be handled through JSON or binary serialization.

ScriptableObject를 공유 변수 및 이벤트 매개체로 활용하면 전역 싱글톤 의존성을 줄이고 프리팹 단위의 독립적인 테스트와 인스펙터 기반 데이터 연결을 수행할 수 있습니다.

Using ScriptableObjects as shared variables and event channels reduces reliance on global singletons and enables isolated prefab testing with Inspector-driven data binding.