Unity Editor로 특정 씬을 작업하다가 플레이 모드를 시작할 때, 특정 씬부터 실행되도록 고정하고 싶을 때가 있습니다. 이럴 때 아래 스크립트 코드를 활용해서 시작 씬을 고정할 수 있습니다.
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.SceneManagement;
[InitializeOnLoadAttribute]
public static class DefaultSceneLoader
{
static DefaultSceneLoader(){
EditorApplication.playModeStateChanged += LoadDefaultScene;
}
static void LoadDefaultScene(PlayModeStateChange state){
if (state == PlayModeStateChange.ExitingEditMode) {
EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo ();
}
if (state == PlayModeStateChange.EnteredPlayMode) {
EditorSceneManager.LoadScene (0);
}
}
}
#endif
중요한 요소는 DefaultSceneLoader 클래스 선언 상단의 어트리뷰트.
해당 어트리뷰트로 선언한 static class 는 컴파일이 되거나 처음 로드됐을 때, Play Mode 에 들어갈 때 생성자가 호출됩니다. 해당 클래스의 LoadDefaultScene 콜백 함수를 통해 특정 씬으로 이동하도록 제어할 수 있습니다.
PlayModeStateChange 열거자(enum)를 참조하여, EnteredPlayMode 일 때 0번 Index 씬을 로드하도록 하면, Play Mode가 시작될 때 첫 번째 씬이 로드되도록 할 수 있습니다. 이 때 빌드 셋팅(Build Setting) 에서 씬 순서를 먼저 설정 해 두어야 한다는 점도 유의해야 합니다.

[InitializeOnLoadAttribute] 어트리뷰트 상세 설명은 아래 링크 참조.
https://docs.unity3d.com/ScriptReference/InitializeOnLoadAttribute.html
Unity - Scripting API: InitializeOnLoadAttribute
Success! Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable. Close
docs.unity3d.com
유니티로 프로그래밍을 하다가 특정 씬부터 시작되는 반복 테스트가 필요할 때, 매번 씬을 이동하지 않고 활용할 수 있어서 편리합니다.
Load a specific scene on play mode
코드 출처 : https://stackoverflow.com/questions/35586103/unity3d-load-a-specific-scene-on-play-mode
Unity3d - Load a specific scene on play mode
Ok, so I'm working on a small project that has a main menu and 10 levels. From time to time I edit different levels, and want to try them out, however I get a NullPointerException as my levels rely...
stackoverflow.com
'유니티 엔진 (Unity Engine)' 카테고리의 다른 글
SmoothDamp 는 어떻게 구현돼있을까? (0) | 2022.05.24 |
---|---|
셰이더 입문서 추천 "아티스트를 위한 유니티 URP 셰이더 입문" (0) | 2022.03.29 |
강력 추천 유니티 입문서 "유니티 교과서" 개정5판 (0) | 2022.03.14 |
Unity TextMeshPro(TMP) 한글 폰트 출력하기 (0) | 2022.01.28 |
유니티 허브(Unity Hub) 3.0.0 정식 버전 둘러봤습니다 (0) | 2022.01.24 |
[C#] Null 조건부 연산자 ?. (null conditional operators) (0) | 2022.01.05 |
유니티 엔진 2021.1 버전 매뉴얼에 새로 추가된 것 (게임 개발 퀵스타트 가이드) (0) | 2021.12.14 |