Skip to content

Instantly share code, notes, and snippets.

@castaneai
Created November 8, 2015 17:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save castaneai/2934b39c9dbeba48b5bd to your computer and use it in GitHub Desktop.
Save castaneai/2934b39c9dbeba48b5bd to your computer and use it in GitHub Desktop.
Unity3d SceneManager
using UnityEngine;
namespace Assets.Scripts
{
public static class GameObjectExtension
{
public static void AddChild(this GameObject parent, GameObject child)
{
var instantiatedObject = GameObject.Instantiate(child);
instantiatedObject.transform.parent = parent.transform;
}
public static void RemoveAllChildren(this GameObject parent)
{
for (var i = 0; i < parent.transform.childCount; i++) {
GameObject.Destroy(parent.transform.GetChild(i).gameObject);
}
}
}
}
using UnityEngine;
namespace Assets.Scripts
{
public abstract class Scene : MonoBehaviour
{
}
}
using UnityEngine.UI;
using UniRx;
namespace Assets.Scripts.Scenes
{
public class Scene1 : Scene
{
public Button switchButton;
void Start()
{
switchButton
.OnClickAsObservable()
.Subscribe(_ => SceneManager.Change<Scene2>());
}
}
}
using UnityEngine.UI;
using UniRx;
namespace Assets.Scripts.Scenes
{
public class Scene2 : Scene
{
public Button switchButton;
void Start()
{
switchButton
.OnClickAsObservable()
.Subscribe(_ => SceneManager.Change<Scene1>());
}
}
}
using UnityEngine;
namespace Assets.Scripts
{
public static class SceneManager
{
private static GameObject getRootGameObject()
{
return GameObject.Find("RootGameObject");
}
private static void destroyCurrentScene()
{
var currentScene = getRootGameObject().GetComponentInChildren<Scene>();
GameObject.Destroy(currentScene.gameObject);
}
public static void Change<T>() where T : Scene
{
destroyCurrentScene();
var prefabPath = string.Format("Scenes/{0}", typeof(T).Name);
var newSceneObject = Resources.Load<GameObject>(prefabPath);
getRootGameObject().AddChild(newSceneObject);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment