Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    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,650
    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,650
    The documentation says it returns a List of whatever you're trying to get. Just iterate over the List.