Hello, I am new to Unity and I am currently making a platformer jumping 2D game and I have no idea how to make a script for my character to respawn when he misses a platform. I have colliders on the bottom of the platforms so if he does fall off he will hit the collider and that’s when I want him to reset(respawn). Please help, If someone could give me the script they used that would be great! I really want to get this to work and it is very frustrating not being able to figure it out…anything helps. Thank you and God bless!
That depends on how you want “respawning” to work. If you have a dedicated location in 3D space to place the character once they fall, then you can reset their transform position, or if it doesnt really matter and the game should restart anyway, you can reload the current scene.
To reload the scene, you have to utilize Unity’s new SceneManager method
//top of script:
using UnityEngine.SceneManagement;
//inside your lose condition:
SceneManager.LoadScene(SceneManager.GetCurrentScene().buildIndex);
To move your characters transform to a specific location:
//assuming you already have a public variable for your player itself:
public Transform player;
public Vector3 spawnPoint;
//in your lose condition:
player.position = spawnPoint;
//there are several ways you can do this exact line of code as well...
Both of these are pseudo code so it may have some spelling errors if you tried to copy/paste and expect it to work, you may have to re-write a few of these (which pressing Ctrl + Space brings up Intelli-sence, which is the thing that tells you what certain functions variables and what not have available to you at the time)
Hello @Viannif
This is a simple script that will reposition your player to a set location after he hits one of your colliders that are set below your platforms.
To make this work though, you need to create a new tag called “DeathZone” and give this tag to all your gameobjects that should respawn the player on contact.
using UnityEngine;
using System.Collections;
public class Respawn : MonoBehaviour {
public Vector3 respawnPosition = Vector3.zero;
void OnCollisionEnter2D(Collision2D coll)
{
if (coll.gameObject.tag == "DeathZone")
{
RespawnPlayer();
}
}
void RespawnPlayer()
{
transform.position = respawnPosition;
}
}
In the RespawnPlayer()-function you can also reset all the other values that you want to be resetted. Hope this can be of help.