- Home /
Hierarchy rendering order problem
I want to change drawing order of GameObjects by changing their sibling indexes. There is the script I use:
public class SiblingTest : MonoBehaviour {
GameObject back;
GameObject item1;
GameObject item2;
GameObject initGameObject(string name, string res) {
GameObject target = new GameObject();
target.name = name;
target.AddComponent<SpriteRenderer>();
target.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>(res);
return target;
}
void Start () {
back = initGameObject("back", "backSprite");
back.AddComponent<BoxCollider2D>();
back.GetComponent<BoxCollider2D>().isTrigger = true;
item1 = initGameObject("item1", "item1Sprite");
item1.transform.SetParent(back.transform);
item2 = initGameObject("item2", "item2Sprite");
item2.transform.SetParent(back.transform);
}
void Update () {
if (Input.GetMouseButtonDown(0))
{
int currIdx = item1.transform.GetSiblingIndex();
item1.transform.SetSiblingIndex((currIdx + 1) % 2);
// here need to add some refresh function
}
}
}
I got predictable result - on every click item1 and item2 change relative positions as childs of back in Hierarchy window. On the contrary of naive assumption, nothing happens on game screen. How do I need to update hierarchy tree to sync current hierarchy view and objects drawing order on game screen? Only way I found is adding { back.SetActive(false); back.SetActive(true);} as refresh. It do work, but left some strange feeling it's wrong and inefficient.
Up question again. For some reasons, our solution for this problem has a bad perfomance at big map. We make social strategy with many objects, it would be nice, if anybody can give us better solution. Thank you
Answer by Suddoha · Sep 10, 2015 at 09:22 AM
What you're trying to do works for the UI which renders the objects according to the order in hierarchy. For sprites, you have to change the sorting order in a sorting layer.
Take this as an example and you'll be fine:
public GameObject sprite1;
public GameObject sprite2;
private SpriteRenderer sr1;
private SpriteRenderer sr2;
void Start()
{
sr1 = sprite1.GetComponent<SpriteRenderer>();
sr2 = sprite2.GetComponent<SpriteRenderer>();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
sr1.sortingOrder = (sr1.sortingOrder + 1) % 2;
sr2.sortingOrder = (sr2.sortingOrder + 1) % 2;
}
}
For some reasons we cant use sorting order for sprites, cause we have over 2000 gameobjects that creates procedural in game. Thats why we use sibling indexes.
Your answer
Follow this Question
Related Questions
How To Sort Prefabs In Hierarchy? 1 Answer
Making UI elements appear in front of other elements 1 Answer
How to change UI rendering order without changing hierarchy 2 Answers
Searching for next available empty text field || instantiating object always on top of the hierarchy 0 Answers
Strange Hierarchy Lag 1 Answer