- Home /
Player Positioning Based on Previous Scene
My character is moving through different rooms, but when they go through doors and I load the scenes the player always goes to the position set in the editor. Is there a way to set the position of the character as the scene is loaded? Here is my script so far:
public string sceneToLoad;
public Vector2 playerPosition;
public VectorValue playerStorage;
public void OnTriggerEnter2D(Collider2D other) {
if (other.CompareTag("Player") && !other.isTrigger)
{
SceneManager.LoadScene(sceneToLoad);
}
}
Thanks!
Answer by tonialatalo · Aug 29, 2020 at 09:21 PM
Two ways:
Add a SceneManager.sceneLoaded event handler, https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager-sceneLoaded.html
put a initialization script in the new scene that sets the player position in it's Start() which gets called automatically when the scene with that object is loaded.
Thanks, @tonialatalo! I think the first way would be better. Can I set a variable in the first scene that the new scene can edit?
Yes. One common way is to have a loader scene, that always sits there and keeps some data. It is normal and fine to have multiple scenes running at one time in Unity. So you could put a script with a sceneLoaded handler there.
Also, you can actually just register a sceneLoaded handler in some class that you use before the scene load. All the C# classes stay in memory even if you switch a scene, at least if you use a static method I think it will work. But it's probably clearer for you to have some gameobject around where you have the handler, so I'd recommend making an extra scene where that sits.
Your answer
Follow this Question
Related Questions
How to "transport" a gameobject when switching scenes? 1 Answer
FPS micrograme transform position of player 2 Answers
Player Sprite Changing Scenes And getting a new camera to follow it and default spawn position 1 Answer
How to add gun to the model, as when it animate, the gun is dis-positioned. 2 Answers
Strange behavior with the Unity car? 0 Answers