- Home /
How to pass a gameobject between scenes
I am trying to find a way to pass my player object between levels in my current project. I have read that I can use Object.Don'tDestroyOnLoad to keep all the player data the same when I pass the player between scenes but I don't know how to pass the object itself. Would I have to instantiate the player into the next scene?
Not only the "data", if an object is marked as DontDestroyOnLoad, that instance of the GameObject won't be destroyed when you change scenes. You can read more about it here:
https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html
DontDestroyOnLoad
will only prevent root objects from being destroyed. So make sure the PlayerGameObject
does not have any parent when the scene loads.
Answer by talyh · Jun 16, 2019 at 02:50 PM
Never had to use it, but wouldn't SceneManager.MoveGameObjectToScene()
work?
This only works on GameObjects being moved to a Scene that is already loaded (additive)
Answer by anglearts · Aug 02, 2020 at 12:02 PM
You do it like this:
private void Awake()
{
var curObjectScripts = FindObjectsOfType<CurObjectScript>();
if (curObjectScripts.Count() > 1)
{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
}
When you don't destroy on load, this game object will live for all scenes. If an additional is created, it is destroyed immediately so that only one instance remains.
Answer by FlimsyEar665012 · Jun 16, 2019 at 04:21 AM
A good way to do this is just to make a testing scene set up what you want to transfer to another scene in that scene and just turn it into a prefab.For example I made a character with a bunch of scripts and animations.I take it and frag it to my library and make new scene and pop him in the scene like nothing happened.
Your answer
Follow this Question
Related Questions
rigidbody.velocity not working on x axis 2 Answers
Calling an Audio Source on one game object from a script on another game object..? 1 Answer
enemy targeting player in different scene 1 Answer
Best workflow for DontDestroyOnLoad method regarding Unity Editor? 1 Answer
How Can I Copy My Gameobject To Other Scene How Can I Copy Gameobject to different scene 1 Answer