- Home /
Unity3D Shooter: Using tags to switch level after killing all enemies.
I am new to Unity and was trying to use tags to know the number of enemies I have in each level and move to the next scene right after eliminating all enemies. This is the script I use on enemy gameobjects. I've also tagged each of them with the "enemy" tag in unity inspector but it still doesn't work when i run the game. After kill all enemies didn´t change to next scene (Sucess!). Any ideas on what I'm doing badly? Any other suggestions? Thanks a lot for the help.
Enemies Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class BadguyScript : MonoBehaviour
{
public GameObject[] enemies;
public int maxHealth;
public int curHealth;
private Animator myAnimator;
private bool isDead;
[SerializeField]
private float DespawnTime = 2.5f;
[SerializeField]
private string DeathAnimHash = "isDead";
void Start()
{
myAnimator = GetComponent<Animator>();
myAnimator.enabled =true;
myAnimator.SetBool (DeathAnimHash ,isDead);
maxHealth = 1;
curHealth = maxHealth;
}
void Update()
{
if (curHealth < 1)
{
isDead = true;
myAnimator.SetBool (DeathAnimHash ,isDead);
Destroy(gameObject,DespawnTime);
}
enemies = GameObject.FindGameObjectsWithTag("enemy"); // Checks if enemies are available with tag "Enemy".
if (enemies.Length == 0)
{
SceneManager.LoadScene("SucessScene"); // Load the scene with name "SucessScene"
}
}
void OnTriggerEnter2D(Collider2D col)
{
if (isDead)
return;
if (col.tag == "bullet")
{
curHealth -= 1;
Destroy(col.gameObject);
}
}
}
Answer by cs120319992 · Nov 01, 2019 at 03:27 PM
Script BadguyScript contain all enemies from map, or this script is on each enemy? And what is logic of this script? You need to create 1 script which contain all enemies and 1 script Enemy which need to set on each enemy For example:
public class Enemies: MonoBehaviour {
public List<Enemy> list = new List<Enemy>();
void Update() {
if(enemies.Count == 0)
// Change scene
}
}
// Script on each enemy
public class Enemy {
// Get class which contains all enemies;
public Enemies enemies;
int health = 100;
void OnTriggerEnter2D(Collider2D col) {
if(isDead)
return;
if(col.tag == "bullet") {
health -= 1;
}
if(health <= 0) {
enemies.list.Remove(this);
Destroy(gameObject);
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612214204im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
2D game Unity5 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Unity3D Shooter - How to switch to next level after all enemies get destroyed? 1 Answer