How to keep the light on/off after changing scenes?

For example, the player is currently at scene_1; he turns the light off; then he goes to scene_2 and does something and goes back to scene_1, and the light in scene_1 should still be off. How can I accomplish this function? Here is the code I use to turn the light on/off, which is attached to the box collider of the light switch. Thank you very much!

BTW, the game is in 2D.

As you may have noticed, Unity destroys every MonoBehaviour when transitioning from one scene to the next. This means, that you need something that stays. There are several ways to accomplish that:

  • make the lightOnOff boolean static. This means it no longer belongs to the concrete Object, but to the class itself. The lifetime of this variable ends with exiting the game. It can be accessed locally like any other variable, so that might be just what you need.
  • If you need different states per scene you can use Dictionary, containing scene name and light status. If used static, this will also persists across scenes
  • You can make a GameObject DontDestroyOnLoad, so Unity keeps it until destroyed yourself. Remember though, that each time you reload a scene with such a GameObject, it’s instantiated again. Here, the Singleton pattern comes in handy.

I think the best way is just to create a static class with all the scenestates you need. It does not need an instance of itself and is just there holding on to your values. For per scene states, a Dictionary is your friend. Either a scene, bool combination, or even a scene, scenestate combination, where scenestate itself is a class holding on to several gamestate variables