- Home /
DontDestroyOnLoad() does not seem to be working.
I have an empty game object with a script attached to it which I intend to use to keep track of variables between level loads. I am using it to keep track of checkpoints. When playing the checkpoint is updated in the gameObject, but when the level is loaded the variables I changed are reset. Here is my code:
var CurrentSpawn : GameObject;
function Start() { CurrentSpawn.SendMessage("SpawnCharacter"); }
function Awake() { DontDestroyOnLoad(this); }
function Update() { print(CurrentSpawn.transform.name); }
A different function changes the spawn point and that part is working, it is just that the spawn point is reset to the original when the level is re-loaded.
Any assistance would greatly be appreciated.
Answer by duck · Mar 16, 2010 at 08:09 PM
That's probably because "CurrentSpawn" references a different object which is destroyed on load. When the new re-set version of the level comes around, that same spawnpoint gameobject is probably considered - by Unity - to be an entirely different new object.
Perhaps instead of storing a reference to that object, you should just store the position of the spawnpoint as a Vector3 (and also the rotation as a Quaternion, if that is required). Because Vector3's and Quaternions are structs, your script will retain its own copy of the values, rather than referencing some other object which gets flushed away when the Load occurs.
Thank you very much for the information! I was able to use it to get my checkpoints working!
Answer by Jaap Kreijkamp · Mar 17, 2010 at 12:02 AM
If you want to keep CurrentSpawn alive as well, you need to tell it not to destroy as well, by the way, to differentiate between vars and functions and objects its practice to start a variable with lowercase:
var currentSpawn : GameObject;
function Start() { currentSpawn.SendMessage("SpawnCharacter"); }
function Awake() { DontDestroyOnLoad(this); DontDestroyOnLoad(currentSpawn); }
function Update() { print(currentSpawn.transform.name); }
Answer by Cyclops · Mar 16, 2010 at 08:28 PM
If an example would help, I posted an Answer in another Question:
How to Keep Information when Reloading a Level.
Which basically points to a demo package I wrote, with code, at:
Simple Demo of a Level Manager
Your answer
Follow this Question
Related Questions
Don't Destroy on Load Function is not working for me, and... 2 Answers
Random object spawn? 1 Answer
Spawning objects from moving objects, In C# 1 Answer
Changing spawning position with C# 2 Answers