Player not moving to new position on trigger.

Hey fellas I’ve got this script that is supposed to teleport the player to a new x,y position in a different scene once he enters it. But instead all it’s doing is moving to a new scene without the player. Here is my code.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Enterandexit : MonoBehaviour
{
    public string SceneName;
    public float xPosition;
    public float yPosition;

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("Player"))
        {
            other.transform.position = new Vector3(xPosition, yPosition, 0);
            SceneManager.LoadScene(SceneName);
            Debug.Log("it worked");
        }
    }
       
}

You’ll have to save the position somehow & apply it when the scene changes (loads).
All that’s happening here is that you’re setting the position, in the current scene, and then changing scenes.

how would one go about doing that?

  1. You could use DontDestroyOnLoad for a script on the player, store the variable there (the game object and its scripts will live through scene changes).
  2. you could use a static variable

Those would be the two most suitable options, I’d say for what you mentioned.

I use DontDestroyOnLoad, SceneManager.sceneLoaded, and GameObject.FindGameObjectWithTag. My player doesn’t get destroyed, and when the scene loads it looks for my new position in that scene since it has the tag I’m looking for.

Thanks gang I was able to figure it out I just created a C# script and used it as my player manager and added “DontDestroyOnLoad” under void update.

1 Like

You can put ‘DontDestroyOnLoad’ in Awake or Start.
Glad ya got it working.

1 Like