Search Unity

loading a level with certain coordinates?

Discussion in 'Scripting' started by matthew77, Sep 24, 2017.

  1. matthew77

    matthew77

    Joined:
    Dec 17, 2016
    Posts:
    29
    Hi. I'm currently using a javascript to load the next level on a collider trigger. Is there a way to add a line of code to it so that I can set the coordinates for where the player spawns?


    Code (csharp):
    1.  #pragma strict
    2.  
    3. var newscene5 : String;
    4.  
    5. function OnTriggerEnter(Col : Collider)
    6. {
    7.     if(Col.CompareTag("Player"))
    8.     {
    9.         Application.LoadLevel (newscene5);
    10.     }
    11. }
    12.  
    13.  
    Thanks in advance to anyone who can help.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    Are you sure you want coordinates? It might be better to have named locations, like "front of house," and then you can put a specific game object with that name in the next scene, and have your player spawn code look for the "front of house" game object and spawn your player there.

    If you are using either coordinates or a named string, one super-simple way to communicate that data to the next level is to store it somewhere such as:

    - in a static variable
    - in a variable inside a persistent game manager class marked as "do not destroy"
    - in PlayerPrefs...
    etc.

    You could also pass persistent data along from scene to scene using the same script above by using a coroutine. The coroutine would do several things in a row:

    - accept the new destination string (or coordinates) for the next scene as an argument
    - mark itself as DontDestroyOnLoad
    - load the new scene (as you did above)
    - in a loop wait for the appearance of the player (i.e., by tagged object)
    - when the player appears, reposition him
    - destroy yourself so the next exit script can do the same steps above.

    These are just some real simple approaches. Each has its strengths and weaknesses and I encourage you to experiment to see how it all goes together.
     
  3. matthew77

    matthew77

    Joined:
    Dec 17, 2016
    Posts:
    29
    Thanks for the response. The loading to named locations sounds like it would be good. Do you have any idea how I would code that into the current script?