에디터에서 작업을 하다 보면 Play 모드 전환 후 메모리가 제대로 해제되지 않아 성능 저하가 발생할 수 있습니다. 이를 방지하기 위해 다음과 같이 메모리를 정리할 수 있습니다.
- Play 모드 종료 후 불필요한 리소스를 해제하여 메모리 누수를 방지합니다.
- 에디터 작업 시 성능을 개선합니다.
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
[InitializeOnLoad][ExecuteInEditMode]
public class EditorModeMemoryManager
{
static EditorModeMemoryManager()
{
EditorApplication.update -= Update;
EditorApplication.update += Update;
}
private static void Update()
{
if (EditorApplication.isPlaying && !EditorApplication.isPlayingOrWillChangePlaymode)
{
ClearMemory();
}
}
private static void ClearMemory()
{
Resources.UnloadUnusedAssets();
System.GC.Collect();
Debug.Log("[Editor] Memory cleared after exiting play mode.");
}
}
#endif
클래스 초기화
- [InitializeOnLoad]와 [ExecuteInEditMode] 속성을 통해, Unity 에디터가 로드되거나 편집 모드에서도 스크립트가 동작하도록 설정합니다.
Play 모드 종료 감지
- EditorApplication.update 이벤트를 활용하여, Play 모드에서 편집 모드로 전환될 때를 감지합니다.
- EditorApplication.isPlaying은 현재 Play 모드 여부를 나타냅니다.
- EditorApplication.isPlayingOrWillChangePlaymode는 Play 모드 전환 중 상태를 나타냅니다. 이를 조합하여 Play 모드가 종료된 시점을 정확히 감지할 수 있습니다.
메모리 정리
- Resources.UnloadUnusedAssets()를 호출하여 사용되지 않는 에셋을 언로드합니다.
- System.GC.Collect()를 호출하여 가비지 컬렉션을 강제 실행합니다.
- Debug 로그를 출력해 메모리 정리가 완료되었음을 알립니다.