0
votes

I have a 2D scene with an orthographic camera that has a Canvas with multiple GameObjects. These objects are actually dialogs that are displayed to the user when they click a button.

All the GameObjects are pre instantiated and I am just using SetActive() to display them or hide them. Now, if a user clicks on a button, they do see the GameObject as expected, but if they click on another button without closing the previous window, the new GameObject(UI Window) displays below the already opened window.

The only real way I have found to change that is by switching the GameObjects hierarchy order inside the Canvas. I do, however, need to change that programmatically, regardless of that.

I have tried changing z values and adding spriterenders with layers, but I keep seeing the same order in my Unity Editor. It only changes if I drag the GameObject and change the position inside the Canvas Hierarchy.

How can I achieve this via script ?

1

1 Answers

2
votes

Your problem is that when your're rendering something inside Canvas the position of GameObject in hierarchy matters. Actually canvas is using order in hierarchy for z-sorting.

But you can affect the order of GameObject in hierarchy in scripts, see Transform.SetSiblingIndex, Transform.SetAsFirstSibling and Transform.SetAsLastSibling if you want to change the position of GameObject in hierarchy