Field value changes after SceneManager.LoadScene been called
Hi, I'm still pretty new to Unity.
After my player changes from one to scene to another I wanted him to change its position if the two scenes are 1 and 2. In the Debug.Log(player.position)
it shows that the position does change but the player is still in the center of the screen. If I have Debug.Log(houseExit)
which is a bool to see if the player has left from the house, it changes to true for a single frame and then back to false, although not specified to do so in the if statement.
public class SceneManager : MonoBehaviour
{
public static SceneManager Instance { get; set; }
public int scene;
public int currentScene;
Transform player;
public Vector3 afterHouse = new Vector3(-13.4f, -0.6f, 3.8f);
bool houseExit = false;
void Awake ()
{
player = GameObject.Find("Player").GetComponent<Transform>();
if (Instance != null && Instance != this)
{
Destroy(gameObject);
}
else
{
Instance = this;
}
}
void Update ()
{
if (houseExit == true)
{
Debug.Log("Works!");
Debug.Log(player.transform.position);
player.transform.position = afterHouse;
Debug.Log(player.transform.position);
}
}
public void Position(int Scene, int CurrentScene)
{
scene = Scene;
currentScene = CurrentScene;
if (scene == 1 && currentScene == 2)
{
player.position = afterHouse;
houseExit = true;
}
}
}
This is the other script that handles the collision:
public class SceneSwitch : MonoBehaviour
{
public Transform player;
public int scene;
public int currentScene;
void OnTriggerEnter ( Collider other )
{
if( other.gameObject.tag == "Player" )
{
SceneManager.LoadScene( scene );
SceneManager.Instance.Position( scene , currentScene );
}
}
}
don't name your component
SceneManager
as it will conflict with existingUnityEngine.SceneManagement.SceneManager
sooner or latercalling SceneManager.LoadScene() will remove all existing GameObjects and load the new scene
If the new scene contains instance of this your SceneManager
script as well as the old one - you might be under the impression that your script state survived the scene change, but it did not. The old instance of SceneManager
was deleted (along with it's state of houseExit
field) and a new SceneManager
was created in the new scene, with it's default value i.e. false
( bool houseExit = false;
).
To fix this you need to learn about a way to make some game objects persist between scene changes. For example, say hi to your new friend DontDestroyOnLoad.
Pozdr.
Thank you for your help! I'll try using DontDestroyOnLoad. I already tried it once on my player script but I guess I must've used it wrong. But still thank you for the info :)
Your answer
Follow this Question
Related Questions
Teleport through walls even with colliders and rigidbody 1 Answer
Having trouble teleporting player in a 2D game 0 Answers
destroying enemy on collision with a bullet 0 Answers
How can i restart a script on collision ? 1 Answer
How to teleport an object to 1 of 8 possible locations on collision? 1 Answer