카테고리 없음

Unity게임개발 2D메타버스 제작 씬 전환 문제 25.02.20

Joon_Im 2025. 2. 20. 15:31

Unity를 이용해 2D메타버스를 제작하는 도중 Scene을 제대로 전환하지 못하는 문제가 생겼다.

여러 서치를 통해 알게 된 Unity에서 SceneManager를 이용하여 씬 전환을 하는 방법을 정리해보았다.

 

1. Scene

게임은 하나의 씬으로 구성되거나, 여러 개의 씬으로 구성될 수 있다. 

또한, 씬은 씬을 하위 요소처럼 불러와 사용할 수 있다.

 

2. Scene Transition

Unity에서 SceneManager Class를 활용해 씬 전환을 다룰 수 있다.

씬은 Single과 Addictive 모드로 불러올 수 있다.

LoadSceneMode.Single은 현재 씬을 종료하고, 새로운 씬을 로드하는 방법이다.

LoadSceneMode.Addictive는 현재 씬 위에 추가적으로 새로운 씬을 불러온다.

 

3. LoadScene

SceneManager 클래스의 LoadScene("SceneName")을 사용하여 씬을 불러온다.

 

using UnityEngine;
using UnityEngine.SceneManagement;

public class Example : MonoBehaviour
{
    void CallNextScene()
    {
        // Only specifying the sceneName or sceneBuildIndex will load the Scene with the Single mode
        SceneManager.LoadScene("SceneName");
        
        /*
        * LoadSceneMode.Single  : 모든 씬을 닫고, 새로운 씬을 불러온다. 
        *  
        * LoadSceneMode.Additive : 현재 씬에 추가적으로 씬을 불러온다.
        */
        SceneManager.LoadScene("SceneName", LoadSceneMode.Single); 
        SceneManager.LoadScene("SceneName", LoadSceneMode.Additive);
        
    }
}

 

4. 데이터 공유

여러 개의 Scene으로 구성된 게임은 Scene들 간의 이동 시 데이터 공유 등이 요구된다. 가령 캐릭터가 A 씬에서 B씬으로 이동할 때, 캐릭터의 HP, MP 등의 데이터를 넘겨주어야 한다. 

 

실제 게임 오브젝트를 넘기는 것이 아닌 데이터를 파일로 저장하고, 새로운 씬이 호출되면, 저장된 값을 불러와 사용하도록 설정한다. 아래의 예제 코드는 PlayerPrefs 컴포넌트를 사용하였다. PlayerPrefs는 각 세션간에 데이터를 저장하고, 접근하도록 구현한 유니티 컴포넌트이다. float, int, string 타입을 지원한다.  

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class NextSceneClass : MonoBehaviour
{
  float healthValue;
  int levelValue;
  // Start is called before the first frame update
  void Start()
  {
    LoadData();
  }
  
  void LoadData()
  {
    // 불러오기
    healthValue = PlayerPrefs.GetFloat("Health");
    levelValue = PlayerPrefs.GetInt("Level");
  }
}

public class Example : MonoBehaviour
{
  public string nextSceneName = "NextScene";
  float healthValue;
  int levelValue;
  // Update is called once per frame
  void Update()
  {
    // Space 키 입력
    if (Input.GetKeyDown(KeyCode.Space))
    {
      LoadNextScene();
    }
  } 
  
  public void LoadNextScene()
  {
    // 데이터를 저장
    SaveData();
    // 비동기적으로 Scene을 불러오기 위해 Coroutine을 사용한다.
    StartCoroutine(LoadMyAsyncScene());
  }
  
  IEnumerator LoadMyAsyncScene()
  {
    // AsyncOperation을 통해 Scene Load 정도를 알 수 있다.
    AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(nextSceneName);
    // Scene을 불러오는 것이 완료되면, AsyncOperation은 isDone 상태가 된다.
    while (!asyncLoad.isDone)
    {
      yield return null;
    }
  }
  
  void SaveData()
  {
    // 저장 
    PlayerPrefs.SetFloat("Health", healthValue);
    PlayerPrefs.SetInt("Level", levelValue);
  }
}

 

5. 개인적인 활용

SceneManager를 활용, LoadScene을 통해 씬 전환을 성공적으로 할 수 있었지만, 이후 데이터를 계속 유지하고 사용하는 것에

PlayerPrefs를 사용해보았지만 원하는대로 잘 되지 않았다.

다중 씬에서 관리를 어떻게 해야할 지 더 생각하고 공부해야될 것 같으며, PlayerPrefs도 잘 활용할 수 있게 되어 데이터를 계속 유지하면서 사용하는 것을 익혀야할 것 같다.

 

https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadScene.html