Posts 유니티 - Play Mode Save Sample
Post
Cancel

유니티 - Play Mode Save Sample

Memo


  • 플레이모드 -> 에디터모드 진입 시 플레이모드의 변경사항 유지
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
public class Sample_PlayModeSave : MonoBehaviour
{
    /***********************************************************************
    *                           Save Play Mode Changes
    ***********************************************************************/
    #region .
#if UNITY_EDITOR
    private class Inner_PlayModeSave
    {
        private static UnityEditor.SerializedObject[] targetSoArr;

        [UnityEditor.InitializeOnLoadMethod]
        private static void Run()
        {
            UnityEditor.EditorApplication.playModeStateChanged += state =>
            {
                switch (state)
                {
                    case UnityEditor.PlayModeStateChange.ExitingPlayMode:
                    //var targets = FindObjectsOfType(typeof(Inner_PlayModeSave).DeclaringType); // 비활성 오브젝트 제외
                    var targets = Resources.FindObjectsOfTypeAll(typeof(Inner_PlayModeSave).DeclaringType); // 비활성 오브젝트 포함
                        targetSoArr = new UnityEditor.SerializedObject[targets.Length];
                        for (int i = 0; i < targets.Length; i++)
                            targetSoArr[i] = new UnityEditor.SerializedObject(targets[i]);
                        break;

                    case UnityEditor.PlayModeStateChange.EnteredEditMode:
                        // NOTE : 플레이 도중/직후 컴파일 시 targetSoArr은 null로 초기화
                        if (targetSoArr == null) break;
                        foreach (var oldSO in targetSoArr)
                        {
                            if (oldSO.targetObject == null) continue;
                            var oldIter = oldSO.GetIterator();
                            var newSO = new UnityEditor.SerializedObject(oldSO.targetObject);
                            while (oldIter.NextVisible(true))
                                newSO.CopyFromSerializedProperty(oldIter);
                            newSO.ApplyModifiedProperties();
                        }
                        break;
                }
            };
        }
    }
#endif
    #endregion
}
This post is licensed under CC BY 4.0 by the author.