How to know which Index a box of multiple game objects is

I have 5 boxes with the same script on each box. In the script, there is a function that changes the color of the box. I want to call that function when my other Game Object, a capsule touches one of the boxes.
Since there are 5 boxes, I find all the Objects (the 5 boxes) with that script and put them in an Array

private CubeMaterial[ ] cubeMatScript;
cubeMatScript = FindObjectsOfType<CubeMaterial>();

Now the problem is, I have to provide an index from that array(, that Box I want to change color) in order to call the function inside the script of the box.
But how do I know which index the Box is that I touched? If I touched the 4th Box, what is the index of that box then, and I don’t know in which order all the boxes are being put in the array (does that depend on the structure in unity hierarchy?)
If my issue is unclear, pls respond/help, thanks.

FindObjectsOfType() will not return the boxes in any order. It will vary from run to run.

If you just want the index in cubeMatScript, then after doing the FindObjectsOfType() call above, iterate the array and stick it into a field (I’ll call it StoredIndex) inside your CubeMaterial script.

for (int i = 0; i < cubeMatScript.Length; i++)
{
  cubeMatScript[i].StoredIndex = i;
}

Then you can just use the .StoredIndex field.

2 Likes