- Home /
Load level and transform
Hi everybody, How do i make my player to spawn in different positions when spawning from different levels. I have a room with two loadLevel colliders. One is a door to other level (outside the room) and other one is a zoomed-in desk scene (static first person view of the desk with various interactions). I want my player to be near the desk when he hits back, and to be near the door when coming from the outside.
Thank you!
Answer by alwayscodeangry · Jul 11, 2014 at 11:43 PM
The main problem here is that you don't have any way of tracking data (in this case the scene your player came from) across scenes.
You need some way of holding persistent data, which won't be lost when you end the scene. There are loads of different ways you could achieve this, all with different pros and cons:
1) Save the data to a file on exiting then read it when you enter the new scene
2) Create a tagged GameObject
with a data script, then call DontDestroyOnLoad()
on the object and find the GameObject
by tag when you enter the scene
3) Create a static
object to keep track of your data (`static` objects exist throughout the lifetime on the application).
Like I said these all have pros and cons, but for your purposes a simple static
object should do the trick.
As an example, create a new C# script for the data object:
using UnityEngine;
using System.Collections;
public static class SceneExitData
{
public static string lastSceneName = "";
}
Then when you exit a scene, possibly in your exit colliders' collision function, set the static data:
SceneExitData.lastSceneName = Application.loadedLevelName;
Finally, when you enter the scene in question, your player's Awake()
or Start()
function can check the data you set in the last scene like so:
switch(SceneExitData.lastSceneName)
{
case "OUTSIDE_SCENE":
// set your transform to the door position
break;
case "ZOOMED_IN_SCENE":
// set your transform to the desk position
break;
default:
Debug.LogWarning("Unhandled scene entry, can't set position");
break;
}
Like I said, this isn't necessarily the best solution in all cases, but it should work for your simple case. I'd recommend reading up on static
objects if you plan to use them further, there are definitely a fair few pitfalls for the unwary!
Thank you very much this was helpful! I writing on javascript but i got the idea, i am making some research on this. I just didn't understand why we are using DontDestroyOnLoad ()