Trouble with DontDestroyOnLoad
I have main scene (street) and many child scenes (houses), to which I can come from the main scene. When I come to one home, then go back to the street, I want to have player object place near that house, where he was. So I need to use DontDestroyOnLoad to remember his position.
But when I come at home, I need to disable player object from the main scene and here my code doesn't work. Also after loading home scene, I can't move cursor un/down, only left/right.
public PS plr;
private GameObject playerOnMainScene;
public void Awake()
{
PlayerSingleton();
DisablePlayerOfMainScene();
}
void PlayerSingleton()
{
if (!plr)
{
DontDestroyOnLoad(gameObject);
plr = this;
}
else
Destroy(gameObject);
}
void DisablePlayerOfMainScene()
{
playerOnMainScene = GameObject.FindGameObjectWithTag("PlayerOnMainScene");
if (SceneManager.GetActiveScene().name != "MainScene") // this code doesn't work
playerOnMainScene.SetActive(false);
else
playerOnMainScene.SetActive(true);
}
Answer by phil_me_up · Mar 08, 2016 at 10:19 AM
I think you might be going about this the wrong way. Whilst I see what you're going for, simply saving the position / state of the player, and then restoring it might be better than trying to keep the player object around.
Depending on what 'home' is and how the game is structured, you might also be better of loading 'home' additively into your street scene and simply shifting camera position etc to simulate changing scenes (but without the overhead of actually changing scenes). This isn't always a good idea though so really depends on your game.
Additionally, your DontDestroyOnLoad applies to the singleton class, not to the 'playerOnMainScene' which may get destroyed between scenes unless that too is a singleton.