- Home /
Help with Scene Changing
So I'm completely stymied trying to figure out why my scene loading isnt working.
The ideal behavior of this script is : load the starting scene the door script on the door in the active scene loads the objects in the next and deactivates them immediately, - Doors in the next scene do not cache their targets The player goes to the door and triggers it All of the gameObjects in the next scene are set to active - This causes the door in that scene to cache its destination, the first. the current scene is unloaded
What actually happens : Everything works as expected until the player gets to the first scene's door The second scene gets activated briefly The door in the second scene caches the first scene as it should Everything in the second scene is deactivated (now there are no active objects in either scene)
Here is the source code:
public class Door : MonoBehaviour
{
public string SceneToLoad;
public Vector2 positionInOtherScene;
bool doOnce = true;
BinaryFormatter bf;
FileStream file;
GameObject player;
Vector3 pos;
Scene current;
Scene otherScene;
GameObject[] otherGos;
GameObject[] currentGos;
void OnEnable()
{
pos = new Vector3(positionInOtherScene.x, positionInOtherScene.y , 0 );
player = GameObject.FindGameObjectWithTag("Player");
current = gameObject.scene;
print("ALoading: " + SceneToLoad);
if(current == SceneManager.GetActiveScene())
{
print("Loading: " + SceneToLoad);
SceneManager.LoadSceneAsync(SceneToLoad,LoadSceneMode.Additive);
SceneManager.sceneLoaded += FinishLoading;
}
}
void FinishLoading(Scene scene, LoadSceneMode lsm)
{
otherScene = SceneManager.GetSceneByName(SceneToLoad);
otherGos = otherScene.GetRootGameObjects();
foreach(GameObject go in otherGos)
{
print("deactivate : " +go.name);
go.SetActive(false);
}
}
void OnDisable()
{
print(gameObject.name + " door is now deactivated");
}
public void Travel()
{
print("hit door in scene " + gameObject.scene);
SceneManager.MoveGameObjectToScene(player,otherScene);
player.transform.position = pos;
SceneManager.UnloadSceneAsync(current);
SceneManager.SetActiveScene(otherScene);
print("Set active scene : " + otherScene.name);
foreach(GameObject go in otherGos)
{
print("activate : " +go.name);
go.SetActive(true);
}
}
void OnTriggerEnter2D(Collider2D col)
{
if(doOnce & col.gameObject.tag=="Player" & otherScene.isLoaded)
{
doOnce = false;
Travel();
}
}
}