hi so I am new with unity and I am making a project for my multimedia HSC project.
I have made it so if the player takes damage it will be destroyed but I want to change it so it plays a different scene which will be my game over scene
help would be really appreciated
this is the code for the health
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class playerhealth : MonoBehaviour
{
public int health;
public int maxHealth = 3;
void Start()
{
health = maxHealth;
}
public void TakeDamage(int amount)
{
health -= amount;
if(health <= 0)
{
Destroy(gameObject);
}
}
}
Add this to the top of your script:
using UnityEngine.SceneManagement;
Now you can load a scene by its name like this:
public void TakeDamage(int amount)
{
health -= amount;
if(health <= 0)
{
Destroy(gameObject);
SceneManager.LoadScene("SceneName");
}
}
If you want to load the scene with a delay you can do this:
public void TakeDamage(int amount)
{
health -= amount;
if(health <= 0)
{
Destroy(gameObject);
Invoke("LoadSceneDelay", 3);
}
}
public void LoadSceneDelay()
{
SceneManager.LoadScene("SceneName");
}
You can use UnityEngine.SceneManagement
like @PingSharp told you. But if the script is on the Destroyed (Or Will Be Destroyed) GameObject, I recommend that you erase the Destroy(gameObject)
line as it will cancel the function of SceneManager.LoadScene("GameOver Scene")
.
Here’s what I recommend:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class playerhealth : MonoBehaviour
{
public int health;
public int maxHealth = 3;
private bool isDead = false;
void Start()
{
health = maxHealth;
}
public void TakeDamage(int amount)
{
if (isDead) return; //If by any chance the player will get hit by another damage.
health -= amount;
if(health <= 0)
{
isDead = true;
Invoke("PlayerDied", 1f); //Give a delay for 1 sec before PlayerDied function plays, usually so that you can play a death animation first
}
}
void PlayerDied()
{
SceneManager.LoadScene("GameOver Scene");
}
}