- Home /
Trying to change scenes after objects are destroyed
I'm making a time trial like game, where you have to destroy targets as fast as possible. Your time is recored and displayed in the next scene. I have been able to apply this to each target; however, when one target is destroyed it'll immeduiately change scenes without the others being destroyed.
using UnityEngine.UI; using UnityEngine; using UnityEngine.SceneManagement; using System.Collections;
public class Target : MonoBehaviour { public float health = 1f; public float score = 0f; public void TakeDamage (float amount) { health -= amount; if (health <= 0f) { Die(); score++; } }
void Die()
{
Destroy(gameObject);
}
private void OnDestroy()
{
SceneManager.LoadScene("FinalTime");
}
}
Answer by Batuhan13 · Feb 25, 2020 at 06:17 AM
Good morning mate =) .I found a simple way to do that .First of all I created a array gameobject named as enemies than I equaled it to GameObject.FindGameObjectWithTag("Enemy"); .After that I created a new for function which checks every enemy if for function founds every enemy dead it will enable bool value. Here the code =)
public class Logic : MonoBehaviour
{
public bool isAllEnemiesDied;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
GameObject[] enemies= GameObject.FindGameObjectsWithTag("Enemy");
if (enemies.Length == 0&&isAllEnemiesDied==true)
{
Debug.Log("You killed all enemies wp=)");
}
for(int i = 0; i < enemies.Length; i++)
{
if (enemies[i] != null&&isAllEnemiesDied==false)
{
isAllEnemiesDied = false;
// Debug.Log("There are a " + enemies.Length + " enemy alive =(");
}
}
}
}
When I writing here I notice that we can make this more shorter =). In update function these two lines will be do same think I guess =)
GameObject[] enemies= GameObject.FindGameObjectsWithTag("Enemy");
if (enemies.Length == 0&&isAllEnemiesDied==true)
{
Debug.Log("You killed all enemies wp=)");
}
Didn't exactly work for me, I was told that I could tell the system that when all objects tagged with target are no longer in the heirarchy I could load the next scene
Your answer
![](https://koobas.hobune.stream/wayback/20220612223927im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
how to destroy all gameobjects with a certain tag? 1 Answer
Unity createNew Game Object after calling a Destroy() 1 Answer
How do I Destroy a Child after Instantiating it? 1 Answer
Need some help an object collider that stops a timer then displays it on another scene 1 Answer
MissingReferenceException after loading a scene, missing object of type text and button. 0 Answers