내일배움캠프

내일배움캠프: 유니티 Conditional을 활용한 분기

pracumj 2024. 12. 2. 23:45

Unity를 이용해 개발을 하다 보면 디버깅이나 테스트를 위해 특정 코드가 에디터에서만 실행되거나, 특정 빌드 설정에서만 실행되도록 해야할 때가 있다. 이 작업을 일일이 수동으로 코드를 썼다 지웠다를 반복 하는 등으로 관리하다 보면 실수가 발생 할 수도 있고 작업의 복잡도 자체가 올라가게 된다. 이를 해결하기 위해  Conditional Attribute  사용할 수 있다!

 

1. 기본적인 Conditional Attribute 활용

Unity scripting symbol reference

 

Unity - Manual: Unity scripting symbol reference

Conditional compilation in Unity Unity scripting symbol reference Platform symbols Unity automatically defines certain symbols based on the authoring and build target platform. These are as follows: Define Function UNITY_EDITOR Scripting symbol to call Uni

docs.unity3d.com

 

Conditional Attribute는 특정 심볼이 활성화된 경우에만 메서드 호출을 포함하도록 설정. 이를 활용하면 개발용 코드가 프로덕션 빌드에 포함되지 않도록 할 수 있다!!! 유니티 메뉴얼에서 기본적으로 제공 되는 심볼을 확인할 수 있다. 

 

예시 코드 

 
using System.Diagnostics; 
using UnityEngine;

public class DebugManager : MonoBehaviour
{
    [Conditional("UNITY_EDITOR")]
    public static void Log(string message)
    {
        Debug.Log(message);
    }

    [Conditional("DEBUG")]
    public static void LogWarning(string message)
    {
        Debug.LogWarning(message);
    }
}

 

2. Scripting Define Symbols로 관리

만약 내가 원하는 심볼이 없다면 이를 추가해줄 수도 있다.

 

추가 방법 

 

Unity에서 Scripting Define Symbols는 Player Settings에서 설정

  1. Unity 메뉴에서 Edit > Project Settings를 선택
  2. Player > Other Settings > Scripting Define Symbols에서 심볼 추가.
    • 예: DEBUG, UNITY_EDITOR_TEST

예시 코드

public class Example : MonoBehaviour
{
 
    [Conditional("ver_DEV")]
    private void DevOnlyFeature()
    {
        Debug.Log("DEV 환경에서만 적용되는 메서드 입니다!");
    }
}

 

Scripting Define Symbols  설정 예시

 

마무리

Conditional AttributeScripting Define Symbols를 활용하면, Unity 프로젝트에서 개발, 테스트 등 다양한 단계에서 코드를 효율적으로 관리할 수 있게 된다. 특히 Debug.Log와 같은 코드가 실제 빌드에서 포함되지 않도록 관리할 수 있어 빌드 크기와 성능을 최적화할 수 있게 된다!!