Is it possible to maintain data across scenes?

I had the idea that I would like to keep track of how many guesses it took to get it right and report that on the “Win Screen”, and then maybe have a different comment from the wizard about whether he was getting any better or worse.

I tried using the same technique we used for the guess, so I created an empty GameObject and added the NumberWizard.cs script as a component to it, and attached the new serialized field I created to new text field that I created, but it didn’t work.

My question is, can I attach the same script to two different GameObjects on two different scenes, so that I can display some data from the script on one scene and then display some other data on a different scene that I switched to? I couldn’t figure out how to make it work.

Thanks,

  • Rob

Hi Rob,

Great question and yes, it certainly is. You in fact cover this in the Laser Defender section of the game. It might be worth waiting until you get to that section where it’s covered and then reverting back to this project to apply what you’ve learnt.

Regarding attaching the same script to multiple GameObjects, you can, but…

  • if these GameObjects are in the same scene you’ll get duplicated behaviour
  • if these GameObjects are in separate scenes, they will be individual instances

Typically the approach would be to create a GameObject which isn’t destroyed upon the next scene loading (DontDestroyOnLoad). Additionally, you may need to consider a singleton pattern so that there is only ever one instance of the thing you are trying to persist.

1 Like

Hey Rob,

Thanks for getting back to me. I knew there had to be a way. :slight_smile: I’m content to know that and come back after I’ve learned that.

Cheers!

  • Rob
1 Like

Hi Rob,

No problem at all. On a related note, you’ll probably have a better grasp of the concept from the other section’s game(s) as what is carried from scene to scene is perhaps more obvious (player score / lives etc).

Enjoy! :slight_smile:

Privacy & Terms