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

Asked

Viewed 817 times

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 are Uis of character faces.

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

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

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

I searched and talked to use the Getsiblingindex function, but I don’t know how to use it in my code. Can anyone help me?

inserir a descrição da imagem aqui

1 answer

6


It’s quite easy. Here’s an example of code, which puts item "9(Clone)" before 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 it wouldn’t be necessary if you were running the code directly in a script attached to that object, because you could use it directly transform). The second line gets the object to have the position changed in the hierarchy among the "brothers" (siblings in English). The third line does what you want, that is, changes the position of that object obtained in the line above.

Note that:

  1. The method GetSiblingIndex It only gives you the index of the object among your brothers. It may be useful in some case that you did not specify, but to change just change indicating the desired position in the method SetSiblingIndex.
  2. Positions are counted from 0, so 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 "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.

inserir a descrição da imagem aqui

P.S.: How to you even realized, there is also the method SetAsLastSibling which puts the item directly as last. The advantage of it is that you don’t need to know the content of the last element (equivalent to the amount of elements - 1).

  • 1

    Very good worked and also used, the Setaslastsibling(); I think it good to put in the answer too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.