I am making a game where you can enter a building. I make the building enter able by using a collider and when I collide with it, it transports me into a new scene. My only issue is that when I exit the building, my character spawns in the middle of the map. I want to script it so that when I exit the building, my character spawns where it entered, not in the middle of the map. Any suggestions?
I think there is many ways you can achieve it.
I will give you one suggestion(first that came to my mind right now):
You can use an anchor(empty gameObject) that represents where the player needs to be placed at the Start of a scene. Then, you must make possible to “change” the position of this anchor from another scene, maybe storing information(PlayerPrefs, or static fields).
In the Awake of the scene(with the anchor), your anchor needs to go to the right position based in the information you previously stored.
After that, your player is spawned, and placed in the anchor’s position, player.position = anchor’s position.
Try this:
public class PlayerSceneAnchor : MonoBehaviour
{
public Vector3 startingPos;
void OnLevelWasLoaded(int level)
{
//Get player and set his position to the startingPos
GameObject player = GameObject.FindGameObjectWithTag("Player");
player.transform.position = startingPos;
Destroy(gameObject);
}
//call this just before you load the next scene to set the player's starting position in the next scene
public static void SetNextSceneStartingPos(Vector3 pos)
{
GameObject g = new GameObject("Player Scene Anchor");
g.AddComponent<PlayerSceneAnchor>().startingPos = pos; //add component to gameobject and set it's starting position to pos
Object.DontDestroyOnLoad(g); //make sure the gameobject does not get destroyed when you load the next scene
}
}
It’s untested, but I’m pretty sure it will work. If not, hopefully it gives you an idea on what to do.
To use, put this script in your project. Do not attach it to a game object. Then, on your collider script, add this line just before loading the next scene:
PlayerSceneAnchor.SetNextSceneStartingPos(exampleStartingPos);