- Home /
remembering variables between scenes
I'm having an issue with creating a spawn point after a level has loaded. So basically, after level 1, it loads level two and loads the default spawn, then after a bonus level, its suppose to return to the 2nd level but with a different spawn. however it keeps using the default spawn. heres my script:
function OnLevelWasLoaded (level : int) {
if(level == 2)
{
loadedPipeLev = true;
}
if(level == 1 && loadedPipeLev == true)
{
Debug.Log("loaded level 2");
transform.position = level2Spawn.transform.position;
}
}
any help would be greatly appreciated.
Answer by syclamoth · Nov 03, 2011 at 01:05 AM
Put the information about what spawns and what doesn't and where in a script on an empty GameObject, and then in your preloader scene (in its start function) use
DontDestroyOnLoad(gameObject);
to stop it getting despawned every time you load a level.
This way you can carry data between scenes, without having to do something cumbersome like use PlayerPrefs.
the problem is when i return to level 2, there are now 2 objects in the scene ins$$anonymous$$d of the one. which means my boolean counters itself and is set to false, preventing my respawn
maybe i should explain. when the player gets through level 2, and goes to the bonus level, after the bonus level the player has to go back to level 2 in a different spawn though. I need a script for that. How would i approach that task?
What I'd do, is have a 'Level Zero' which gets loaded at the very beginning, which contains your 'spawn whatever and where' script, which upon loading tells it to go to your 'Level One' (after using DontDestroyOnLoad(gameObject)). You then never go to that level again, so the object doesn't get loaded a second time!
Or, if you want to use it like a hard reset, have an 'OnLevelWasLoaded' function which tests for
if(level == 0) Destroy(gameObject);
and then to reset the game, just use Application.LoadLevel(0);
Answer by CreativeStorm · Nov 03, 2011 at 01:11 AM
You can save the spawn points coords using PlayerPrefs like so:
PlayerPrefs.SetFloat("SpawnPosX", 10.0);
PlayerPrefs.SetFloat("SpawnPosX", 10.0);
PlayerPrefs.SetFloat("SpawnPosZ", 10.0);
or using an gameObjects Vector3 with preventing its destruction:
function Awake ()
{
DontDestroyOnLoad (transform.gameObject);
}
Or you save using one of this methods an int to indicate an spawn pont in the players awake/start function.
hope that points you an solution ;)