Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Resolved Problem deleting an object from a list of objects from another script.

Discussion in 'Scripting' started by sergio_bermudez_tsapp1ma2021, Apr 28, 2021.

  1. sergio_bermudez_tsapp1ma2021

    sergio_bermudez_tsapp1ma2021

    Joined:
    Jan 21, 2021
    Posts:
    2
    Hi everyone!

    So I have 2 scripts set up. The first script is the EnemyManager which handles the creation of zombies objects that will spawn in each wave. And I have a script to handle the behavior of each individual zombies.

    When I create the zombies I placed them to a list of GameObjects called enemiesList[ ] to keep track of how many zombies are currently still there. If all the zombies are taken out, the next wave will spawn. The condition for this is if enemiesList.count == 0, then I can spawn the next wave.

    The problem I'm having now is when I delete a zombie object when it dies, I can't remove it from the enemiesList so the first wave never ends.

    Thank you very much for your help!

    BaseScript using UnityEngine; using System.Collections.Generic; using System.Collections;

    The EnemyManager script:

    Code (CSharp):
    1. public class EnemyManager : MonoBehaviour
    2. {
    3.     public PlayerHealth playerHealth;
    4.     public EnemyHealth enemyHealth;
    5.  
    6.     public GameObject Zombunny;
    7.     public GameObject Zombear;
    8.     public GameObject Hellephant;
    9.  
    10.     public float spawnTime = 3f;
    11.     public int waveNumber;
    12.  
    13.     public Transform[] spawnPoints; // Array de spawns
    14.     public List<GameObject> enemiesList;
    15.  
    16.     public int[] zombieBunnyPerWave;
    17.  
    18.     void Start()
    19.     {
    20.         waveNumber = 1;
    21.         Spawn(waveNumber);
    22.  
    23.         //InvokeRepeating("Spawn", spawnTime, spawnTime); // Pasado el primer spawnTime se llama a la función Spawn y luego cada vez que pase el spawnTime infinitamente
    24.         // Sustituirlo luego por un contador de oleadas
    25.     }
    26.  
    27.     private void Update()
    28.     {
    29.         if (enemiesList.Count == 0) // O era .Lenght?
    30.         {
    31.             waveNumber++;
    32.         }
    33.     }
    34.  
    35.     void Spawn(int waveNumber)
    36.     {
    37.         if (playerHealth.currentHealth <= 0f) // Si el player está muerto deja de generar enemigos
    38.         {
    39.             return;
    40.         }
    41.         /*
    42.         int spawnPointIndex = Random.Range(0, spawnPoints.Length); // Elige aleatoriamente un spawn de la lista, hacer que en vez de cogerlos aleatoriamente spawneen de esos puntos la cantidad que le des de cada uno
    43.  
    44.         Instantiate(Zombunny, spawnPoints[spawnPointIndex].position, spawnPoints[spawnPointIndex].rotation); // Instancia un enemigo en la posición de los spawnPoints
    45.         enemiesList.Add(enemy);
    46.         */
    47.         if (waveNumber == 1)
    48.         {
    49.  
    50.             /*for (int i = 0; i < zombieBunnyPerWave[0]; i++) //
    51.             {
    52.                 Instantiate(Zombunny, spawnPoints[0].position, spawnPoints[i].rotation);
    53.                     Instantiate(Zombunny, spawnPoints[1].position, spawnPoints[i].rotation);
    54.                 Instantiate(Zombunny, spawnPoints[2].position, spawnPoints[i].rotation);// Genera enemigos en los 3 spawns                                
    55.                 enemiesList.Add(Zombunny);
    56.             }*/
    57.  
    58.             for (int i = 0; i < zombieBunnyPerWave[0]; i++)
    59.             {
    60.                 for (int z = 0; z < spawnPoints.Length; z++)
    61.                 {
    62.                     GameObject newZombunny = Instantiate(Zombunny, spawnPoints[z].position, spawnPoints[i].rotation);
    63.                     enemiesList.Add(newZombunny);
    64.                 }
    65.  
    66.             }
    67.  
    68.             // Otros dos for para los otros dos enemigos
    69.         }
    70.  
    71.  
    72.         // Hacer 5 oleadas
    73.     }
    74.  
    75.  
    76.     public void deleteFromList(GameObject newZombunny) // Antes lo tenía sin lo de dentro de los paréntesis
    77.     {      
    78.         enemiesList.Remove(newZombunny);
    79.     }
    80. }

    The EnemyHealth script:

    Code (CSharp):
    1. public class EnemyHealth : MonoBehaviour
    2. {
    3.     public int startingHealth = 100; // Valor de vida inicial
    4.     public int currentHealth; // Valor de vida actualizada
    5.     public float sinkSpeed = 2.5f; // Velocidad a la que el cuerpo del enemigo desaparece
    6.     public int scoreValue = 10; // Puntos al matar a este enemigo
    7.     public AudioClip deathClip; // Sonido al morir el enemigo
    8.  
    9.     Animator anim;
    10.     AudioSource enemyAudio;
    11.     ParticleSystem hitParticles;
    12.     CapsuleCollider capsuleCollider;
    13.  
    14.     public EnemyManager enemyManager;
    15.  
    16.     bool isDead; // Si el enemigo está muerto
    17.     bool isSinking; // Si el cuerpo del enemigo debe desaparecer
    18.  
    19.     void Awake()
    20.     {
    21.         enemyManager = GetComponent<EnemyManager>();
    22.         anim = GetComponent<Animator>();
    23.         enemyAudio = GetComponent<AudioSource>();
    24.         hitParticles = GetComponentInChildren<ParticleSystem>();
    25.         capsuleCollider = GetComponent<CapsuleCollider>();
    26.  
    27.         currentHealth = startingHealth; // Inicializar la salud actual
    28.     }
    29.  
    30.  
    31.     void Update()
    32.     {
    33.         if (isSinking) // Si la variable hundirse está en vd se va a ir hundiendo el cuerpo del enemigo poco a poco
    34.         {
    35.             transform.Translate(-Vector3.up * sinkSpeed * Time.deltaTime); // Se hunde en base a la velocidad marcada en sinkSpeed
    36.         }
    37.     }
    38.  
    39.  
    40.     public void TakeDamage(int amount, Vector3 hitPoint)
    41.     {
    42.         if (isDead)
    43.             return; // Comprobamos si el enemigo está muerto, en el caso de que ya lo esté directamente salimos
    44.  
    45.         enemyAudio.Play();
    46.         currentHealth -= amount; // Restar vida al enemigo
    47.  
    48.         hitParticles.transform.position = hitPoint; // Posiciono con el transform el efecto de partículas de recibir un disparo y lo activamos
    49.         hitParticles.Play();
    50.  
    51.         if (currentHealth <= 0)
    52.         {
    53.             Death();
    54.         }
    55.     }
    56.  
    57.  
    58.     void Death()
    59.     {
    60.         isDead = true;
    61.  
    62.         capsuleCollider.isTrigger = true; // Significa lo mismo que la línea de abajo
    63.         //capsuleCollider.enabled = false; // Desactivo el capsule collider
    64.  
    65.         anim.SetTrigger("Death"); // Reproducir la animación de morir
    66.  
    67.         enemyAudio.clip = deathClip; // Reemplazar el clip de sonido de recibir daño por el de morir
    68.         enemyAudio.Play();
    69.  
    70.         //enemyManager.deleteFromList(this.gameObject);
    71.         enemyManager.enemiesList.Remove(this.gameObject);
    72.     }
    73.  
    74.  
    75.     public void StartSinking() // Se llama desde un evento de la anim de morir del enemigo
    76.     {
    77.         GetComponent<UnityEngine.AI.NavMeshAgent>().enabled = false; // Desahibilitar el movimiento del enemigo
    78.         GetComponent<Rigidbody>().isKinematic = true; // Deja de verse influenciado por las físicas del entorno
    79.         isSinking = true; // El enemigo empieza a descender
    80.         ScoreManager.score += scoreValue; // Incrementa la puntuación del player
    81.  
    82.         //enemyManager.deleteFromList(gameObject);
    83.         //enemyManager.enemiesList.Remove(this.gameObject);
    84.  
    85.         Destroy(gameObject, 2f); // Se destruirá en 2 segs para ver como se hunde en el suelo
    86.     }
    87.  
    88. }
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,724
    Delete line 21 from your enemy script:
    Code (CSharp):
    1. enemyManager = GetComponent<EnemyManager>();
    That line doesn't make sense. It is implying that the EnemyManager script exists on the same object as your Enemy script, which obviously is not true.

    Then around line 62 of the enemy spawner script, add this to set the enemyManager reference on the newly spawned enemy.
    Code (CSharp):
    1.                     GameObject newZombunny = Instantiate(Zombunny, spawnPoints[z].position, spawnPoints[i].rotation);
    2.                     enemiesList.Add(newZombunny);
    3.                     newZombunny.GetComponent<EnemyHealth>().enemyManager = this;
     
  3. sergio_bermudez_tsapp1ma2021

    sergio_bermudez_tsapp1ma2021

    Joined:
    Jan 21, 2021
    Posts:
    2
    It worked!!! Thank you very much for your help! :)