How can you load next the level after you destroy the last clone c#
I am almost complete with my game but I am just stuck on one part. I have to implement some statement that says when the last clone is destroyed the next level is loaded. Except I do not know how to do that. I have a respawner which makes like 20 clones of a sphere and when I collide with them they disappear. After 20 clones have been destroyed I want to advance to the next level. Can anyone help me out?.
Here's my respawner:
using UnityEngine;
using System.Collections;
public class spawner : MonoBehaviour
{
public GameObject objectToSpawn;
public int numberOfEnemies;
private float spawnRadius = 5;
private Vector3 spawnPosition;
// Use this for initialization
void Start ()
{
SpawnObject();
}
void Update () {}
void SpawnObject()
{
for (int i= 0; i < numberOfEnemies; i++)
{
spawnPosition = transform.position + Random.insideUnitSphere * spawnRadius;
Instantiate(objectToSpawn, spawnPosition, Quaternion.identity);
}
}
}
Here's my BoxDestroy:
using UnityEngine;
using System.Collections;
public class BoxDestroy : MonoBehaviour {
public int x;
void Start ()
{
x=10;
}
void OnTriggerEnter(Collider collider)
{
if (collider.gameObject.tag == "Player")
{ x--;
Destroy(gameObject);
}
if(x==0){
Application.LoadLevel(0);
}
}
} Any help is appreciated! :)
Answer by ZefanS · Nov 18, 2015 at 06:20 AM
If you tag your enemies with a tag such as "Enemy", then you could do something like this in Update():
if (GameObject.FindWithTag("Enemy") == null)
{
Application.LoadLevel("NextLevel");
}
Or you could keep a count of how many enemies are left in the Scene and do something like:
if (enemyCount <= 0)
{
Application.LoadLevel("NextLevel");
}
Neither of these solutions are very elegant because the check gets called unnecessarily every frame. Alternatively, you could do something a bit smarter, and call a method to do a check like this only when you destroy a clone. Something like:
public void CheckForEnemiesLeft()
{
if (GameObject.FindWithTag("Enemy") == null)
{
//Do any finishing up
Application.LoadLevel("NextLevel");
}
}
This all assumes that you know which level you want to load next. For this I would use a level management GameObject that would keep track of which level should be loaded next. You would create this in the first scene and then call DontDestroyOnLoad() so that it persists throughout all the scenes.
The CheckForEnemiesLeft() function could be part of the level management script.
Hope this helps.
Your answer
Follow this Question
Related Questions
Destroy() not removing the object all the time (Coroutine used) 0 Answers
How to correctly count number of objects? 2 Answers
How can I change this script so that each instantiated prefab spawns a set amount faster 0 Answers
Unity3D: Objects destroy automatically 0 Answers
Adding a unique element from one list to another list 2 Answers