Search Unity

How can I find how many objects in a scene have a certain tag in C#?

Discussion in 'Getting Started' started by jbsgroup, Dec 13, 2022.

  1. jbsgroup

    jbsgroup

    Joined:
    Aug 27, 2022
    Posts:
    6
    I'm working on a project, and part of that project is keeping a door closed until all the enemies in the previous room are killed. Is there any way for me to get how many objects have the "Enemy" tag in the update function so I can see if there's any still alive?
    Edit: If you have another way to keep track of the enemies killed that would be simpler that works too. I just need some way to make unity know when all the enemies have been killed
     
    Last edited: Dec 13, 2022
  2. AngryProgrammer

    AngryProgrammer

    Joined:
    Jun 4, 2019
    Posts:
    490
    You can plan your entire gameplay scenario and store its data in one place. Such a class in many different productions is called GameManager. In this class you can store some counters, structures, lists that will help you keep track of the gameplay.

    So you don't have to search the entire game scene at all, because what is on it or disappears you check off in GameManager. For example, every enemy killed at this point is not only doing Destroy(gameObject), but remembering to subtract it from the counter also.
     
  3. RichAllen2023

    RichAllen2023

    Joined:
    Jul 19, 2016
    Posts:
    1,026
    A bit unoriginal, but if it works, don't knock it, a lot of games do that, you can't leave the room till all the baddies are dead.