Skip to content

Instantly share code, notes, and snippets.

@starikcetin
Last active July 27, 2022 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save starikcetin/81c2b6e5d4badd35a8ecae90169cc493 to your computer and use it in GitHub Desktop.
Save starikcetin/81c2b6e5d4badd35a8ecae90169cc493 to your computer and use it in GitHub Desktop.
SceneUtils, GetAllRootGameObjects, DontDestroyOnLoadScene, etc.
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
public static class SceneExtensions
{
/// <summary>
/// Returns whether the given scene contains the given component on any of its GameObjects.
/// </summary>
public static bool HasComponent<T>(this Scene scene)
{
return scene.GetRootGameObjects().Any(rootGameObject => rootGameObject.GetComponentsInChildren<T>().Any());
}
}
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
public static class SceneUtils
{
private static Scene? _dontDestroyOnLoadScene = null;
public static Scene DontDestroyOnLoadScene
{
get
{
_dontDestroyOnLoadScene ??= GetDontDestroyOnLoadScene();
return _dontDestroyOnLoadScene.Value;
}
}
/// <summary>
/// Returns the Scene that objects go in when we call <see cref="Object.DontDestroyOnLoad"/> on them.
/// </summary>
/// <remarks>
/// Hacky because Unity... See:<br/>
/// https://forum.unity.com/threads/editor-script-how-to-access-objects-under-dontdestroyonload-while-in-play-mode.442014/#post-3570916<br/>
/// https://github.com/yasirkula/UnityRuntimeInspector/blob/12bd2d85fd5e571756d2783338d9a17706e87263/Plugins/RuntimeInspector/Scripts/RuntimeHierarchy.cs#L1523
/// </remarks>
private static Scene GetDontDestroyOnLoadScene()
{
GameObject temp = null;
try
{
temp = new GameObject();
Object.DontDestroyOnLoad(temp);
var dontDestroyOnLoadScene = temp.scene;
Object.DestroyImmediate(temp);
temp = null;
return dontDestroyOnLoadScene;
}
catch (System.Exception e)
{
Debug.LogException(e);
return new Scene();
}
finally
{
if (temp != null)
{
Object.DestroyImmediate(temp);
}
}
}
public static IEnumerable<Scene> GetAllLoadedScenes(bool includeDontDestroyOnLoadScene = true)
{
for (var i = 0; i < SceneManager.sceneCount; i++)
{
yield return SceneManager.GetSceneAt(i);
}
if (includeDontDestroyOnLoadScene)
{
yield return DontDestroyOnLoadScene;
}
}
public static IEnumerable<GameObject> GetAllRootGameObjects(bool includeDontDestroyOnLoadScene = true)
{
static GameObject[] GetRootGameObjects(Scene scene) => scene.GetRootGameObjects();
return GetAllLoadedScenes(includeDontDestroyOnLoadScene).SelectMany(GetRootGameObjects);
}
public static bool HasComponentInAnyLoadedScene<T>(bool includeDontDestroyOnLoadScene = true)
{
return GetAllLoadedScenes(includeDontDestroyOnLoadScene).Any(SceneExtensions.HasComponent<T>);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment