Day 5 Solutions




Respawn / Checkpoint System

This is a simple system for respawning the player at a checkpoint.
If the player runs out of health, you would call “RespawnAtCheckpoint()” to send them back.
Alternatively, if you dont have a health system, you can just send the player back whenever they touch an enemy or hazard with getcomponent and oncollisionenter2d / ontriggerenter2D.

using UnityEngine;

public class Respawn : MonoBehaviour
{

    //we will use a vector2 to store the position of the last checkpoint
    Vector2 Checkpoint;

    // Start is called before the first frame update
    void Start()
    {
       //set the first checkpoint position
        //right where the player starts, so if they die before hitting a checkpoint
        //they go back to the start
        Checkpoint = transform.position;
    }

    //use this function to respawn at the last checkpoint
    //if using health, make sure to also reset health
    public void RespawnAtCheckpoint()
    {
        transform.position = Checkpoint;
    }

    //use this function to set a new checkpoint
    //I would write another script that calls
    //this in ontriggerenter2D with getcomponent
    //like how our inventory system works...
    public void SetCheckpoint(Vector2 position)
    {
        Checkpoint = position;
    }
}


Load a Scene

For this to work you NEED TO ADD using UnityEngine.SceneManagement; to the top of your script, and also make sure ALL THE SCENES YOU WANT IN YOUR GAME ARE ADDED TO BUILD SETTINGS

using UnityEngine;
//MAKE SURE you include UnityEngine.SceneManagement, it is necessary to load levels!
using UnityEngine.SceneManagement;

public class LoadLevelDemo : MonoBehaviour
{
    public string LevelNameToLoad;

    void LoadTheLevel()
    {
        //use SceneManager.LoadScene like this to load levels
        SceneManager.LoadScene(LevelNameToLoad);
    }
}