Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Author: Daniele Giardini - http://www.demigiant.com
- // Created: 2020/10/25
- using System;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.SceneManagement;
- using Object = UnityEngine.Object;
- namespace Demigiant.DemiTools.DeUnityExtended
- {
- public static class DeSceneUtils
- {
- #region Public Methods
- /// <summary>
- /// Returns all root DontDestroyOnLoad GameObjects, or an empty list if none was found.<para/>
- /// WARNING, expensive method with allocations (can be partially avoided by passing an existing DontDestroy GameObject):<para/>
- /// - new list creation<para/>
- /// - new GameObject creation-then-destruction (necessary to detect the DontDestroy scene, avoidable if anyDontDestroyGameObject is provided)
- /// </summary>
- /// <param name="anyDontDestroyGameObject">Providing this will avoid having to create and destroy a temporary gameObject during this process</param>
- public static List<GameObject> GetDontDestroyRootGameObjects(GameObject anyDontDestroyGameObject = null)
- {
- List<GameObject> result = new List<GameObject>();
- Scene dontDestroyScene;
- if (anyDontDestroyGameObject != null) {
- dontDestroyScene = anyDontDestroyGameObject.scene;
- dontDestroyScene.GetRootGameObjects(result);
- } else {
- const string tmpGuid = "bb179a0d-94b2-4008-ad78-f3871dc82ba6";
- GameObject tmpGO = new GameObject(tmpGuid);
- Object.DontDestroyOnLoad(tmpGO);
- dontDestroyScene = tmpGO.scene;
- Object.Destroy(tmpGO);
- dontDestroyScene.GetRootGameObjects(result);
- int tot = result.Count;
- for (int i = 0; i < tot; ++i) {
- if (result[i].name != tmpGuid) continue;
- result.RemoveAt(i);
- break;
- }
- }
- return result;
- }
- /// <summary>
- /// Sorts all GameObjects in the DontDestroy scene.<para/>
- /// WARNING, expensive method with allocations (can be partially avoided by passing an existing DontDestroy GameObject):<para/>
- /// - new list creation<para/>
- /// - new GameObject creation-then-destruction (necessary to detect the DontDestroy scene, avoidable if anyDontDestroyGameObject is provided)
- /// </summary>
- /// <param name="anyDontDestroyGameObject">Providing this will avoid having to create and destroy a temporary gameObject during this process</param>
- public static void SortDontDestroyGameObjectsAlphabetically(GameObject anyDontDestroyGameObject = null)
- {
- List<GameObject> allRootDontDestroyGos = GetDontDestroyRootGameObjects(anyDontDestroyGameObject);
- allRootDontDestroyGos.Sort(SortGameObjectsByName);
- int tot = allRootDontDestroyGos.Count;
- for (int i = 0; i < tot; ++i) allRootDontDestroyGos[i].transform.SetSiblingIndex(i);
- }
- #endregion
- #region Methods
- static int SortGameObjectsByName(GameObject a, GameObject b)
- {
- return string.Compare(a.name, b.name, StringComparison.InvariantCultureIgnoreCase);
- }
- #endregion
- }
- }
Add Comment
Please, Sign In to add comment