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

Feedback Error to find Objects in Unity using an array

Discussion in 'Scripting' started by 3dartmike, Sep 30, 2022.

  1. 3dartmike

    3dartmike

    Joined:
    Apr 1, 2020
    Posts:
    13
    I am new to Unity programming.
    I'm trying to make a for loop collect 100 images in the void Start. But the script doesn't work.
    The images are imported as sprites and have a tag called "puntosVerdes" I also added a script called the same "puntosVerdes". But I can't find them even with the search by Tags or by "FindObjectOfType". Could someone give me a hand, thank you very much.

    Code (CSharp):
    1.  
    2. public GameObject[] imagenesPuntosVerdes;
    3. public GameObject imagenContenedor;
    4. int cantidadImagenesSecuencia;
    5. private const string Tag = "puntosVerdes";
    6.  
    7. void Start()
    8.     {
    9.         cantidadImagenesSecuencia = 100;
    10.         imagenesPuntosVerdes = new GameObject[cantidadImagenesSecuencia];
    11.         for (int i = 0; i < cantidadImagenesSecuencia; i++)
    12.         {
    13.             Debug.Log("Cantidad puntos verdes");
    14.          //el bucle funciona, pero no me encuentra las imagenes.
    15.          imagenesPuntosVerdes[i] = FindObjectOfType<puntosVerdes>().gameObject;  
    16.            
    17.         }
    18.     }
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,596
    FindObjectOfType will return the first object found, pretty much the same one every time. You want FindObjectsOfType, the plural version.

    It's also pretty slow, I personally would rather just have the scripts add themselves to a List.
     
  3. 3dartmike

    3dartmike

    Joined:
    Apr 1, 2020
    Posts:
    13
    Hello RadRedPanda and thank you very much for answering, your solution creates another problem for me that I will now try to solve. I have tried many ways. I would like to know the solution you are talking about. Thanks a lot! Untitled-1.jpg
     
  4. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,596
    The documentation says it returns a List of whatever you're trying to get. Just iterate over the List.