I have this current script but whenever I try it works fine but my z position is -1 I need it to be 2 help either need a better re spawn method or a fix
IEnumerator respawn()
{
player.GetComponent<Transform>().position = new Vector3(checkpx, 1, 2);
Destroy(GetComponent<Rigidbody2D>());
yield return new WaitForSeconds(1);
player.AddComponent<Rigidbody2D>();
player.GetComponent<Transform>().position = new Vector2(checkpx, 2);
Debug.Log("RIP DEAD");
health = 3;
}
EDIT:
Sorry just noticed to you never have to get the transform as a component, all MonoBehaviours have it available by default. So this line:
player.GetComponentTransform.position = new Vector2(checkpx, 2);
line should be changed to:
player.transform.position = new Vector3(checkpx, 2,2);
because unity is a 3d engine even the 2d objects can be positioned in 3d. So when you make a 2d game in unity it is really a 2.5d game, that is why there is more overhead than a 2d game engine. The closest thing to actual 2d is using the canvas. You can also set the position of something after you instantiate it, which is how i usually do it, because the instantiation and setting the position will happen in the same frame you can set the position and other attributes after you instantiate it.
I just take away full control until the player is correctly placed
public bool canmove;
if (canmove) {
// Some movement script
}
IEnumerator respawn()
{
Debug.Log("RIP DEAD");
canmove = false;
player.transform.position = new Vector3(checkpx, 2, 2);
Destroy(GetComponent<Rigidbody2D>());
yield return new WaitForSeconds(.4f);
player.AddComponent<Rigidbody2D>();
player.transform.position = new Vector3(checkpx, 2, 2);
health = 3;
yield return new WaitForSeconds(.4f);
canmove = true;
}