AntonioTorro
AntonioTorro

Reputation: 199

Unity 5 C# - How to Change Scenes and Import all Resources from Last Scene

I'm not sure how to switch scenes and bring all of my resources with me. I do understand that upon load of new scene, the previous scene gets destroyed on load. I've explored some with DontDestroyOnLoad() but had no luck with what I'm trying to do.

I tried to make my player controller a prefab and simply put him into the next scene; however, I returned a heck of a lot of errors because of the many scripts I have. Mostly stuff like checkpoint, HP bars, and even the weapon.

What I need to know is how to import everything into the next scene. How do I do this without having to recode or even re-make all of the stuff that I need?

Upvotes: 1

Views: 596

Answers (3)

HalloweenJack
HalloweenJack

Reputation: 281

If you need to import every object from the previous scene, then what's the point in creating a new one?

What you could do is saving the objects positions into a file and then loading that file back on the next scene or try (again) with DontDestroyOnLoad();

I recommend to check the documentation of Unity about this function.

If you want an individual object not to be destroyed on the scene change then on the void Awake() function of Unity make a DontDestroyOnLoad(this.gameObject);

Upvotes: 2

You're looking for LoadSceneMode.Additive. This is the second parameter of the LoadScene method and will load the new scene into the current one.

Upvotes: 2

agiles231
agiles231

Reputation: 71

Could you provide more information? I ask because it seems from your description that

DontDestoryOnLoad

should accomplish what you want but you say it does not. As long as the object holding the components whose states you want to save is persisted into the next scene using that method, then all of those components' states should be persisted as well. Please elaborate and we can possibly provide a better answer. As for how to use it to save the state of every game object:

GameObject[] allObjects = UnityEngine.Object.FindObjectsOfType<GameObject>();
foreach(GameObject go in allObjects) {
   if (go.activeInHierarchy) { /* and any other logic you want. Maybe like !isTerrain */
      Object.DontDestroyOnLoad(go);
   }
}

For the above code, I ripped it from https://answers.unity.com/questions/329395/how-to-get-all-gameobjects-in-scene.html

Upvotes: 1

Related Questions