Home > OS >  Load next level if amount of enemies is zero
Load next level if amount of enemies is zero

Time:12-12

This is my first time making a 2d game. I'm trying to load a scene if the amount of objects with tag "Enemy" is zero. Line 22 doesn't seem to work. I don't get any errors.

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

public class LevelLoader : MonoBehaviour
{

    public Animator transition;

    public float transitionTime;

    public GameObject enemyPrefab;
    public GameObject[] enemy;


    // Update is called once per frame
    void Update()
    {
        if (enemy == null)
        {
            enemy = GameObject.FindGameObjectsWithTag("Enemy");
            Debug.Log("null!");
            LoadNextLevel();
        }
    }

    public void LoadNextLevel()
    {
        StartCoroutine(LoadLevel(SceneManager.GetActiveScene().buildIndex   1));
    }

    IEnumerator LoadLevel(int levelIndex)
    {
        transition.SetTrigger("Start");

        yield return new WaitForSeconds(transitionTime);

        SceneManager.LoadScene(levelIndex);
    }
}
enemy = GameObject.FindGameObjectsWithTag("Enemy");

CodePudding user response:

I believe that it's because the variable enemy is of type array and not a list. Arrays are more difficult to deal with and are of a fixed size.

Instead, consider using a List:

List<GameObject> enemy = new List<GameObject>();

Here are some additional resources to assist you with understanding the difference between arrays and lists.

The difference/when to use each

CodePudding user response:

Initially enemy is null.

So, in the first frame (the first time Update() is called) it satisfies the if condition and then assign something to enemy.

Then, in the second and later frames, enemy is not null anymore, so it does not satisfies if (enemy == null) condition and the lines in the if statement does not be executed. It means that, the lines enemy = GameObject.FindGameObjectsWithTag("Enemy") and LoadNextLevel(); will never be executed after the first frame.

My suggestion is that rewrite the Update() just like this:

void Update() {
    enemy = GameObject.FindGameObjectsWithTag("Enemy"); // get "Enemies" first
    // then do something by using it
    if (enemy == null) {
        Debug.Log("null!");
        LoadNextLevel();
    }
}
  • Related