'player not moving to requested position - unity 2D
my goal is when in radius of a door, when you press down you move scene and get moved to the position of the door but no matter what i try, my player wont move there. any ideas?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Door : MonoBehaviour
{
public string sceneToWarpTo;
public string doorScene;
public float doorLocationX;
public float doorLocationY;
public GameObject player;
private float x;
private float y;
// Start is called before the first frame update
void Start()
{
x = player.transform.position.x;
y = player.transform.position.y;
}
// Update is called once per frame
void Update()
{
}
IEnumerator LoadFixThing()
{
//yield on a new YieldInstruction that waits for 5 seconds.
yield return new WaitForSeconds(1);
}
public void OnTriggerStay2D(Collider2D coll) {
if (coll.tag == "Player"){
if(Input.GetKeyDown(KeyCode.S) || Input.GetKeyDown(KeyCode.DownArrow)){
Debug.Log("Enter Door");
Debug.Log("warping to " + sceneToWarpTo + " from " + doorScene);
SceneManager.LoadScene(sceneToWarpTo);
LoadFixThing();
player.transform.position = new Vector2(doorLocationX, doorLocationY);
Debug.Log("player pos: " + player.transform.position);
Debug.Log("door pos: " + this.transform.position);
Debug.Log(player.name);
}
}
}
}
i dont really know what more to say but it keeps saying my question requires more info so thank you for reading my question :)
Solution 1:[1]
Hmm... shouldn't you call SceneManager.Loadscene after moving the player? Try that first..
Solution 2:[2]
If you are opening a new scene, the current player object is destroyed along with the previous scene. If you want to persist it, you can use DontDestroyOnLoad
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jkimishere |
| Solution 2 | Andriy Marshalek |
