Search Unity

Player not moving to new position on trigger.

Discussion in 'Scripting' started by Dude_Mojo, Jun 24, 2017.

  1. Dude_Mojo

    Dude_Mojo

    Joined:
    Jul 14, 2016
    Posts:
    13
    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.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class Enterandexit : MonoBehaviour
    7. {
    8.     public string SceneName;
    9.     public float xPosition;
    10.     public float yPosition;
    11.  
    12.     void OnTriggerEnter(Collider other)
    13.     {
    14.         if (other.CompareTag("Player"))
    15.         {
    16.             other.transform.position = new Vector3(xPosition, yPosition, 0);
    17.             SceneManager.LoadScene(SceneName);
    18.             Debug.Log("it worked");
    19.         }
    20.     }
    21.        
    22. }
     
  2. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    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.
     
  3. Dude_Mojo

    Dude_Mojo

    Joined:
    Jul 14, 2016
    Posts:
    13
    how would one go about doing that?
     
  4. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    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.
     
  5. Pixelith

    Pixelith

    Joined:
    Jun 24, 2014
    Posts:
    577
    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.
     
  6. Dude_Mojo

    Dude_Mojo

    Joined:
    Jul 14, 2016
    Posts:
    13
    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.
     
    Pixelith likes this.
  7. methos5k

    methos5k

    Joined:
    Aug 3, 2015
    Posts:
    8,712
    You can put 'DontDestroyOnLoad' in Awake or Start.
    Glad ya got it working.
     
    Pixelith likes this.