Home > Enterprise >  How to load death scene in C#/unitygames?
How to load death scene in C#/unitygames?

Time:12-02

haven't posted on here before but I have been trying for a while to create a game and would like a death/game over sort of scene to appear when the player loses all 3 of their lives. I have a functioning game manager and my player can lose lives (they have 3). This is all being done in unity games and is 2d (idk if that helps). I currently have other stuff in my scene loader script that works fine so I will post the whole thing but I am having issues with the bottom most code! Thank you!

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

public class SceneLoader : MonoBehaviour
{
  public string scenename;
  public GameManager GM;
 

 private void OnTriggerEnter2D(Collider2D collision)
  {
    if(collision.tag == "Player")
    {
      SceneManager.LoadScene(scenename);
    }
  }


    private void Deathscene()
    {
      if(GM.LifeTotal == 0)
        {
           SceneManager.LoadScene(Bob); 
        }
    }

}

Gamemanager script 

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

public class GameManager : MonoBehaviour
{
public int PotionsCollected = 0;
public int LifeTotal = 3;

    public Text PotionsOutput;
    public Text LifeOutput;
    void Update()
    {
        PotionsOutput.text = "Potions: "   PotionsCollected;
          LifeOutput.text = "Life: "   LifeTotal;
    }

    public void CollectPotion()
    {
        PotionsCollected  ;
    }
    public void UsePotion()
    {
        PotionsCollected--;
    }
    public void LoseLife()
    {
        LifeTotal--;
    }
}

CodePudding user response:

What you can do is from your Unity Editor go to File->Build Settings and then drag and drop inside the active scenes window your death scene.

Then an index will be generated on the right side of the window and you can use that index to load the scene. like this:

SceneManager.LoadScene("Use your generated index");

NOTE: Use your index as a number and not as a string.

UPDATED Solution:

public void LoseLife() 
{
    LifeTotal--; 

    if(LifeTotal <= 0)
    {
         SceneManager.LoadScene("Use your generated index");
    }
}

I supposse LoseLife() it's called when the enemy attacks your player.

  • Related