Layermask

Hello again guys. Previously i asked about autoaim for 2D and it works thanks to you guys. However, as i begin to progress more to the game, i realised that i need my script to shoot multiple enemy that have a different tag. Beforehand, i only used GameObject.FindGameObjectsWithTag("x"); and i observed it only work for enemy that have the tag x. So is there any ways i can add more tag to the script ? I learned about layermask and thought it might help but it doesn't seem to solve my case. Deeply appreciate it.

void UpdateTarget()
    {
        GameObject[] enemies = GameObject.FindGameObjectsWithTag(enemyTag);
        float shortestDistance = Mathf.Infinity;
        GameObject nearestEnemy = null;
        foreach (GameObject enemy in enemies)
        {
            float distanceToEnemy = Vector3.Distance (transform.position, enemy.transform.position);
            if(distanceToEnemy < shortestDistance)
            {
                shortestDistance = distanceToEnemy;
                nearestEnemy = enemy;
            }
        }
}

just need to change the enemyTag to support multiple tag. thats all... Thanks

Unfortunately Unity does not support multiple tags on the same object. The team is aware of this but at this point in time it's not yet on the roadmap to make any changes to this.

The easiest solution would be to have multiple calls to GameObject.FindGameObjectsWithTag though that might get quite a performance impact depending on the amount of objects in your scene.

A better solution would be to use Object Pooling in your enemy spawner (and any other spawners) that keep track of all the GameObjects its instantiated and have those be publicly available to other classes. Then you can simply ask the spawner for the list of objects that are currently active in the scene which is much more performant and gives you better control over which objects you want to use.

You can find plenty of tutorials on how to implement Object Pooling either on the forums, Google, Youtube or any other place where you can find Unity Tutorials.

There are also plenty of libraries created by the community already like on Unity Pooling by Cory Leach on Github which handles the pooling for you and make it easier to gain access to the objects you need without bad coding practices of multiple dependencies as it's all shared through ScriptableObjects.

Hope this helps!