How can I avoid using GetComponent() in a for loop?

Hi there,

Currently I use this loop to set properties from a script on an array of objects:

for (int i = 0; i < columnfiller; i++)
            {
                GameObject newtile = Instantiate(Tile, new Vector3(0.0f + j, 5.0f + i, 0.0f), Quaternion.identity);
                newtile.GetComponent<TileDefault>().interactionlock = true;
                newtile.GetComponent<TileDefault>().RandomizeMe();
                newtile.GetComponent<TileDefault>().droplength=columnfiller;
                newtile.GetComponent<TileDefault>().DropTileDown();
            }

Now I know that GetComponent<>() is not recommended to use many times because of performance, so I would like to set it up in the class constructor.
Question is, I don’t know how to do that and even if that’s a smart thing to do?

Any insights much appreciated, Thanks!

you can cache it once:

for (int i = 0; i < columnfiller; i++)
             {
                 GameObject newtile = Instantiate(Tile, new Vector3(0.0f + j, 5.0f + i, 0.0f), Quaternion.identity);

TileDefault tf =   newtile.GetComponent<TileDefault>();

                 tf.interactionlock = true;
                 tf.RandomizeMe();
                 tf.droplength=columnfiller;
                tf.DropTileDown();
             }

You can avoid GetComponent completely in this case. Just declare your “Tile” variable where you assign your prefab reference as “TileDefault” instead of “GameObject”:

public TileDefault Tile;

// [ ... ]

for (int i = 0; i < columnfiller; i++)
{
    TileDefault newtile = Instantiate(Tile, new Vector3(0.0f + j, 5.0f + i, 0.0f), Quaternion.identity);
    newtile.interactionlock = true;
    newtile.RandomizeMe();
    newtile.droplength = columnfiller;
    newtile.DropTileDown();
}

When you pass in the reference to a component of a prefab, Instantiate would still clone the whole gameobject but instead of returning the reference to the gameobject it would return the reference to that component on the cloned object.