Unity change the order of a game object via code by C #

4

Well I have a Game Object called Party Frames.

Inside it I have several prefabs with different names (their names are the character IDs) and they are UIs of character faces.

The only thing I want is to change the order of these objects from different names via code because when I change the prefab order it automatically changes the position of the UI and I need to do an order scheme where I place the UI the way it I want Because depending on the speed of the character the UI comes first, and after it passes the character's turn it goes to the end of the line.

I do not know if I was clear, any doubt is just to speak.

In case the order I want to change are 1 (clone), 2 (clone), etc.

I researched and talked about using the GetSiblingIndex function, however I do not know how to use it in my code. Can anyone help me?

    
asked by anonymous 06.10.2017 / 18:33

1 answer

6

It's fairly easy. Here is an example code that puts the item "9 (Clone)" before the item "7 (Clone)":

Transform pf = GameObject.Find("Party Frames").transform;
Transform c9 = pf.Find("9(Clone)");
c9.SetSiblingIndex(1);

The first line gets the object Transform of the parent object (and would not be necessary if you are executing the code directly in a script attached to that object because you could directly use transform ). The second line gets the object to have the position changed in the hierarchy of the "brothers" ( siblings in English). The third line does what you want, that is, it changes the position of that object obtained in the above line.

Please note:

  • The GetSiblingIndex method only returns the index of the object from your siblings. It may be useful in some case that you did not specify, but to change it, simply change it by indicating the desired position in the SetSiblingIndex / a>.
  • Positions are counted from 0, so that the first position is 0, the second is 1, the third is 2, and so on. As in the example I wanted to put the item "9 (Clone)" (which was the 4th) before the "7 (Clone)" (which was the 2nd), just put the object in index 1 (remember? 0 is the first, 1 is the second ...). Unity automatically "pushes" the others forward, placing the object in the position you requested.
  • PS:Like you even noticed , there is also the method SetAsLastSibling which places the item directly as the last. The advantage of it is that you do not need to know the index of the last element (equivalent to the number of elements - 1).

        
    08.10.2017 / 20:51