Reputation: 229
I have a scene which opens up when game starts. Lets call this scene 'Start'. It has a new game button which starts the game by loading a new scene. This scene is called 'Game'. After the game ends in 'Game' Scene, I want to open 'Start' scene.
I am using Application.LoadLevel("Start") for this. But when 'Start' scene is opened again all gameobjects are deleted, except the ones I use DontDestroyOnLoad() on. If I pause the game in 'Start' scene, the gameobjects come back but with null in scripts wherever they were assigned in inspector.
I cant use DontDestryOnLoad on every object in 'Start' scene as they are completely useless for the 'Game' scene.
I have also tried Application.LoadLevelAdditive but would give the same result as DontDestroyOnLoad.
Thus the transition that I want is Start -> Game -> Start -> Game ......
And each time the scene may start with fresh gameobjects or reuse the existing ones. But objects in 'Start' are not required in 'Game' scene but only a score object of 'Game' scene is required in 'Start', on which I have applied DontDestroyOnLoad. This object will write the score on an object in 'Start' scene.
Upvotes: 0
Views: 1055
Reputation: 7824
Anything that is created in one scene will be destroyed the moment you change scenes, except if the object is static
or you call DontDestroyOnLoad()
on that object.
Therefore, it is logically correct to go from Start --> Game --> Start --> Game
without any side-effects. You must, however, avoid duplicate creations of Objects, for example:
The Game
scene creates a Score
object.
public class Game : MonoBehaviour
{
public GameObject score;
void Awake()
{
score = GameObject.Find("Score");
if(score == null)
{
score = Instantiate(scorePrefab) as GameObject;
DontDestroyOnLoad(score);
}
}
}
The code ensures that the next time you reload the Game
scene, there won't be an extra Score
object floating around.
Upvotes: 2