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. Dismiss Notice

How to use FindGameObjectsWithTag on List

Discussion in 'Scripting' started by alimrafeek, Jun 17, 2020.

  1. alimrafeek

    alimrafeek

    Joined:
    May 22, 2018
    Posts:
    14
    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.

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class Test : MonoBehaviour
    6. {
    7.     private GameObject[] enemy;
    8.     public List<GameObject> enemies;
    9.    
    10.     void Start()
    11.     {
    12.         enemy = new GameObject[10];
    13.     }
    14.  
    15.  
    16.     void Update()
    17.     {
    18.         if (Input.GetButtonDown("Fire"))
    19.         {
    20.             Debug.Log("Spawning...");
    21.             FindEnemy();
    22.         }
    23.     }
    24.  
    25.     void FindEnemy()
    26.     {
    27.         enemy = GameObject.FindGameObjectsWithTag("Enemy");
    28.         foreach (GameObject e in enemy)
    29.         {
    30.             enemies.Add(e);
    31.         }
    32.     }
    33.  
    34. }
    35.  
     
  2. Lurking-Ninja

    Lurking-Ninja

    Joined:
    Jan 20, 2015
    Posts:
    9,913
    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

    Code (CSharp):
    1. enemies.AddRange(GameObject.FindGameObjectsWithTag("Enemy"));
    should work as well.
     
  3. alimrafeek

    alimrafeek

    Joined:
    May 22, 2018
    Posts:
    14
    Thanks Man, That worked