Skip to content

Instantly share code, notes, and snippets.

@nekomimi-daimao
Created November 26, 2024 16:48
Show Gist options
  • Save nekomimi-daimao/bfd0e870d222f962d2d99c583ea1a757 to your computer and use it in GitHub Desktop.
Save nekomimi-daimao/bfd0e870d222f962d2d99c583ea1a757 to your computer and use it in GitHub Desktop.
Unityのシーンライフサイクルをログに出力する
using System;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.ResourceManagement.ResourceProviders;
using UnityEngine.SceneManagement;
namespace Project.Scripts
{
public sealed class SceneLifeCycleLogger : MonoBehaviour
{
private string _sceneName;
private int _id;
private void Awake()
{
_sceneName = this.gameObject.scene.name;
_id = this.gameObject.scene.handle;
Debug.Log($"{_sceneName} - {_id} - Awake");
}
private void Start()
{
Debug.Log($"{_sceneName} - {_id} - Start");
}
private void OnEnable()
{
Debug.Log($"{_sceneName} - {_id} - OnEnable");
}
private void OnDisable()
{
Debug.Log($"{_sceneName} - {_id} - OnDisable");
}
private void OnDestroy()
{
Debug.Log($"{_sceneName} - {_id} - OnDestroy");
}
}
#if UNITY_EDITOR
[UnityEditor.CustomEditor(typeof(SceneLifeCycleLogger))]
public sealed class SceneLifeCycleLoggerEditor : UnityEditor.Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
UnityEditor.EditorGUILayout.Space();
loadSceneName = UnityEditor.EditorGUILayout.TextField("Scene Name", loadSceneName);
loadSceneMode = (LoadSceneMode)UnityEditor.EditorGUILayout.EnumPopup(this.loadSceneMode);
UnityEditor.EditorGUILayout.Space();
UnityEditor.EditorGUILayout.LabelField("Scene");
if (GUILayout.Button("Load"))
{
LoadScene();
}
if (GUILayout.Button("UnLoad"))
{
UnLoadScene();
}
UnityEditor.EditorGUILayout.LabelField("Addressable");
if (GUILayout.Button("Load"))
{
LoadAddressable();
}
if (GUILayout.Button("UnLoad"))
{
UnLoadAddressable();
}
}
public string loadSceneName;
public LoadSceneMode loadSceneMode = LoadSceneMode.Additive;
private SceneInstance _sceneInstance;
private async void LoadScene()
{
Debug.Log($"Load {loadSceneName} Start");
await SceneManager.LoadSceneAsync(loadSceneName, loadSceneMode);
Debug.Log($"Load {loadSceneName} End");
}
private async void UnLoadScene()
{
Debug.Log($"UnLoad {loadSceneName} Start");
await SceneManager.UnloadSceneAsync(loadSceneName);
Debug.Log($"UnLoad {loadSceneName} End");
}
private async void LoadAddressable()
{
Debug.Log($"Addressable Load {loadSceneName} Start");
var operationHandle = Addressables.LoadSceneAsync(loadSceneName, loadSceneMode);
await operationHandle;
_sceneInstance = operationHandle.Result;
Debug.Log($"Addressable Load {loadSceneName} End");
}
private async void UnLoadAddressable()
{
Debug.Log($"Addressable UnLoad {loadSceneName} Start");
await Addressables.UnloadSceneAsync(_sceneInstance);
Debug.Log($"Addressable UnLoad {loadSceneName} End");
}
}
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment