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

Remove a prefab from list

Discussion in 'Scripting' started by witcher101, Feb 1, 2018.

  1. witcher101

    witcher101

    Joined:
    Sep 9, 2015
    Posts:
    516
    I have a list of enemies. I am instantiating this enemy from list.
    After the enemy is destroy i wana remove this enemy from list.
    How do i do this
    On destroy function i am using enemylist.remove(this.gameobject);

    But it doesnt since spawned enemy is an instance of prefab from list.

    So how do i do this

    Thanks
     
  2. Zonlib

    Zonlib

    Joined:
    Apr 15, 2014
    Posts:
    39
    You should add the prefabs name to instances name or to the name of an its child. You just check the name when you need to remove prefab
    Ex:
    Code (CSharp):
    1.  
    2.         GameObject enemyInstance = Instantiate(enemylist[index]);
    3.         enemyInstance.transform.Find("preb_name").name = enemylist[index].name;
    ...and remove

    Code (CSharp):
    1.         foreach(GameObject obj in enemylist)
    2.         {
    3.             if(obj.name == this.transform.Find("preb_name").name)
    4.             {
    5.                 enemylist.Remove(obj);
    6.                 break;
    7.             }
    8.         }
     
  3. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,146
    If you are instantiating from a list and you don't need to use that enemy prefab again, just remove it after you instantiate a clone. Or if you are creating several copies, just remove it when you create your last copy.
     
  4. witcher101

    witcher101

    Joined:
    Sep 9, 2015
    Posts:
    516
    I need to remove enemy from list only after enemy is dead
     
  5. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,146
    Then you need to record something about the index they are in. Either have a variable for the name, a variable for the Gameobject, or if you can only have one enemy from the list out at a time, then just use the index. @BiDuc gives you an example that would be similar to a string variable by naming the newly created object instead.