Skip to content

Commit be3fc35

Browse files
committed
feat(Util): Add with active scene
1 parent db03fbd commit be3fc35

File tree

1 file changed

+36
-4
lines changed

1 file changed

+36
-4
lines changed

Assets/JCSUnity/Scripts/Util/JCS_Util.cs

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -880,15 +880,47 @@ public static void ReattachSelf(RectTransform trans, ReattachCallback callback)
880880
/// <returns> Return the newly spawned game object. </returns>
881881
public static GameObject InstantiateToScene(GameObject original, Scene scene)
882882
{
883-
GameObject newObj = MonoBehaviour.Instantiate(original);
883+
GameObject newObj = null;
884884

885-
RemoveCloneString(newObj);
885+
WithActiveScene(scene, () =>
886+
{
887+
newObj = MonoBehaviour.Instantiate(original);
886888

887-
SceneManager.MoveGameObjectToScene(newObj, scene);
889+
RemoveCloneString(newObj);
890+
});
888891

889892
return newObj;
890893
}
891894

895+
/// <summary>
896+
/// Execute with in the active scene without losing the
897+
/// current scene.
898+
/// </summary>
899+
/// <param name="scene"> Target scene we want to execute. </param>
900+
/// <param name="action"> The execution body. </param>
901+
public static void WithActiveScene(Scene scene, System.Action action)
902+
{
903+
Scene oldScene = SceneManager.GetActiveScene();
904+
905+
// If the same scene, just execute and leave.
906+
if (oldScene == scene)
907+
{
908+
if (action != null)
909+
action.Invoke();
910+
911+
return;
912+
}
913+
914+
// Switch to new scene.
915+
SceneManager.SetActiveScene(scene);
916+
917+
if (action != null)
918+
action.Invoke();
919+
920+
// Revert back to old scene.
921+
SceneManager.SetActiveScene(oldScene);
922+
}
923+
892924
/// <summary>
893925
/// Spawn an animate object.
894926
/// </summary>
@@ -1017,7 +1049,7 @@ public static Object FindObjectByType(System.Type type)
10171049
/// <summary>
10181050
/// Retrieves a list of all loaded objects of Type type.
10191051
/// </summary>
1020-
public static Object[] FindObjectsByType(System.Type type)
1052+
public static UnityEngine.Object[] FindObjectsByType(System.Type type)
10211053
{
10221054
#if UNITY_2023_1_OR_NEWER
10231055
return UnityEngine.Object.FindObjectsByType(type, FindObjectsSortMode.None);

0 commit comments

Comments
 (0)