유니티

[유니티] LoadScene 주의할 점

유니티 게임 개발 2024. 12. 26. 15:28

SceneManager.LoadScene 으로 씬을 로드하게 되면 ,

현재 씬의 모든 오브젝트와 변수들은 기본적으로 메모리에서 사라지고

초기화가 된다.

 

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManager;

public class GameManager : MonoBehaviour
{
	float a = 1;
    
    void Start()
    {
    	a = 10;
    	SceneManager.LoadScene("SampleScene"); // a = 1로 초기화 됨
    }
}

 

 

 

따라서 게임 내에서 최고기록을 사용할 때,

LoadScene을 거친다면,

float bestScore; 변수를 활용해 저장할 게 아니라,

PlayerPrefs를 활용해 사용해야 한다.

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManager;

public class GameManager : MonoBehaviour
{
    void Start()
    {
    	PlayerPrefs.SetInt("BestScore", 100);
    	SceneManager.LoadScene("SampleScene");
        // 로드 씬을 거쳐도 "BestScore"의 메모리에 있는 값은 그대로 남아있음
    }
}