How to use FindGameObjectsWithTag on List

I want to store some gameobjects on a list using FindGameObjectsWithTag method. Currently i am creating a temporary array to return from the method, and then copy each elements individually.

Is there any other way where I don’t need to create a temporary array?

Thanks.

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

public class Test : MonoBehaviour
{
    private GameObject[] enemy;
    public List<GameObject> enemies;
   
    void Start()
    {
        enemy = new GameObject[10];
    }


    void Update()
    {
        if (Input.GetButtonDown("Fire"))
        {
            Debug.Log("Spawning...");
            FindEnemy();
        }
    }

    void FindEnemy()
    {
        enemy = GameObject.FindGameObjectsWithTag("Enemy");
        foreach (GameObject e in enemy)
        {
            enemies.Add(e);
        }
    }

}

What is this for?

And what is this for in your script?

Because you’re trying to load a list of game objects in a variable called enemy. You really need to work on the naming.

You can add another collection to your lists and arrays with the AddRange method. So in theory the

enemies.AddRange(GameObject.FindGameObjectsWithTag("Enemy"));

should work as well.

1 Like

Thanks Man, That worked