- Home /
How to get variables from other scenes
I've looked at questions other people made and I can't seem to get them to work. I want to save myLives variable to another level. I've tried putting DontDestroyOnLoad but I just get a crash when I put it in, I know I'm doing it wrong.
public class Lives : MonoBehaviour {
void OnGUI() {
GUI.Label(new Rect(10, 10, 100, 20), "Lives left: " + myLives.ToString());
}
public int myLives = 3;
public Transform destination;
void OnTriggerEnter ( Collider col ){
col.transform.position = destination.position;
col.transform.rotation = destination.rotation;
myLives--;
}
void Update(){
if(myLives <= 0){
Application.LoadLevel(0);
}
}
}
Answer by benni05 · May 04, 2014 at 02:25 PM
Your crash most likely results from consecutive loading of level 0 after your variable has been decreased to zero. Make sure you load your level just once to be able to debug properly. I.e. make the loading dependent on another variable. Apart from that DontDestroyOnLoad is your friend as you have mentioned. You would put it preferably in the Awake method of your script that is attached to a GameObject that will persist then when loading a new level.
http://docs.unity3d.com/Documentation/ScriptReference/Object.DontDestroyOnLoad.html
Answer by Jeff-Kesselman · May 04, 2014 at 03:09 PM
For something simple like this, its a lot easier just to use a static variable. eg
public static class MyWorldState{
public static int Lives;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613144226im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to make the level screen????? 0 Answers
keeping a loadout from the customization screen into the game 1 Answer
making variables work in two scenes 1 Answer
Reuse Scenes just changing some variables?? 1 Answer
accesing objects variables 1 Answer