Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

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

Discussion in 'Scripting' started by freesumo, Aug 10, 2020.

  1. freesumo

    freesumo

    Joined:
    Jul 12, 2020
    Posts:
    1
    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.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,517
    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.

    Code (csharp):
    1. for (int i = 0; i < cubeMatScript.Length; i++)
    2. {
    3.   cubeMatScript[i].StoredIndex = i;
    4. }
    Then you can just use the
    .StoredIndex
    field.
     
    Dextozz and StarManta like this.