Search Unity

Basic restart function

Discussion in 'Getting Started' started by Yegor42069, Feb 20, 2023.

  1. Yegor42069

    Yegor42069

    Joined:
    Dec 5, 2022
    Posts:
    26
    Im making this basic platformer game and I added a restart function but when i run the game the scene doesn't reload here is my code

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.SceneManagement;
    5.  
    6. public class PlayerLife : MonoBehaviour
    7. {
    8.     private Rigidbody2D rb;
    9.     void Start()
    10.     {
    11.         rb = GetComponent<Rigidbody2D>();
    12.     }
    13.  
    14.  
    15.     private void OnCollisionEnter2D(Collision2D collision)
    16.     {
    17.         if (collision.gameObject.CompareTag("Trap"))
    18.         {
    19.             Die();
    20.         }
    21.     }
    22.     private void Die()
    23.     {
    24.         rb.bodyType = RigidbodyType2D.Static;
    25.     }
    26.  
    27.     private void RestartLevel()
    28.     {
    29.         SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    30.     }
    31. }
    32.  
     
  2. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,157
    Nothing in that code is calling RestartLevel().
     
  3. Yegor42069

    Yegor42069

    Joined:
    Dec 5, 2022
    Posts:
    26
    I understand that but I dont know how to fix it what do I do
     
  4. RichAllen2023

    RichAllen2023

    Joined:
    Jul 19, 2016
    Posts:
    1,026
    On line 27 you have a space between the brackets, remove that, and it might work :)
     
  5. AngryProgrammer

    AngryProgrammer

    Joined:
    Jun 4, 2019
    Posts:
    490
    I don't really know what the question is about. As for the method itself, it's correct, you just don't call it anywhere. Logically, the level restart is probably after the character dies, so put the RestartLevel() call inside the Die().