Being spawned inaccurately on level load.

Hey so I’ve been working on a simple 2D platformer.

To make things simpler I created an empty game object called Spawn Point with a very small script to instantiate the player:

public GameObject player;
public GameObject spawnPoint;

	void Start ()
    {
        Instantiate(player);
        player.transform.position = spawnPoint.transform.position;
    }

However, whenever the level restarts or a new level loads the character can appear quite a distance away from it. Usually about 2 or 3 “units” which can make the player start on the other side of the wall and not on the intended starting position… Like on top of a hole or on one of the items to collect.

I really have no idea why this could be happening, I even tried settings the position before instantiating (and didn’t get any errors for the player not existing yet, funnily enough) but that still didn’t work…

After resetting the level or dying (resetting the level therefore) it always instantiates correctly though…

Please let me know if you need more details, I really don’t know what could be causing it and I don’t want to tell you everything as it might be unrelated xD

You should first check if the prefab position is set to 0,0,0.
What your code is doing now is instantiating the player, then modifying the position of the actual prefab, not the instance you just created.

You could either do somethink like:

         player.transform.position = spawnPoint.transform.position;
         Instantiate(player);

this will edit the prefabs position before instantiating it.

You could also do something like:

 public GameObject player;
 GameObject instPlayer;
 public GameObject spawnPoint;
 
     void Start ()
     {
         instPlayer = Instantiate(player) as GameObject;
         instPlayer.transform.position = spawnPoint.transform.position;
     }

but easiest should simply be:

 public GameObject player;
 public GameObject spawnPoint;
 
     void Start ()
     {
         Instantiate(player, spawnPoint.transform.position, spawnPoint.transform.rotation);
     }

Code is untested, but it should work.
I hope it helps!