Obstacles

With the level created and the character able to navigate it, it is now important to add Obstacles.

Implementing Obstacles requires two scripts.

The first script goes on the player and will perform two actions.

  • When the game loads, the characters start position is saved.
  • When the player hits an Obstacle, the code tells the character to go back to the start position.

The second script goes onto any obstacles that will reset the player and will perform one action.

  • If the player hits the obstacle, the player is then told to return to the start position.

Example ResetPlayer Code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ResetPlayer : MonoBehaviour
{
    // Creates a variable that stores the X, Y and Z position of the player
    private Vector3 startPosition;

    // This code runs when the game starts
    void Start()
    {
        // Store the position where the player spawned
        startPosition = transform.position;
    }

    // This function is called by the obstacle when the player hits it
    public void ResetToStart()
    {
        // Set the position of the player to the startPosition stored at the start of the game
        transform.position = startPosition;
    }
}

Example DeathZone Code

using UnityEngine;

public class DeathZone : MonoBehaviour
{
    // This function looks for collisions with 
    private void OnTriggerEnter2D(Collider2D collision)
    {
        // Check if the object is named "Player"
        if (collision.gameObject.name == "Player")
        {
            // Access the ResetPlayer script on the Player
            ResetPlayer player = collision.GetComponent<ResetPlayer>();

            // Make sure the script exists otherwise it will error
            if (player != null)
            {
                // tell the player to ResetToStart
                player.ResetToStart();
            }
        }
    }
}

Target

You should be able to add Obstacles to your game that reset the players position.