- Home /
Bring UI Image To Front Programmatically
I have a UI image in the new UI system, it's the child of a canvas with several other UI elements (buttons, images, text). I have an image residing at the "back", and I want to move it to the "front" programmatically.
Image img = GetComponent<Image>();
img.z = 1000;
This code obviously doesn't work, and I'm having one hell of a time finding a solution that isn't "drag it lower in the hierarchy".
There should be a dead simple straight forward single function call answer, and I can't find it.
Answer by YoungDeveloper · Jun 01, 2015 at 11:52 PM
If your canvas is screen space - overlay, child elements are rendered from top to bottom, so lower elements are rendered last - on top of previous. Simply set it as last transform.
Thanks that did the trick, I'm a little disappointed in Unity for not providing an index based ordering function when that is clearly the underlying structure.
You can in fact do index manipulations with transform children. For example this will take last child and transfer it on the front lines.
Transform lastchild = this.transform.GetChild(this.transform.childCount-1);
lastchild.SetSiblingIndex(0);
Hi and sorry about digging up this post but is it possible to bring the first child of the UI to the front ? That's my example : alt text
This titles bar is made of 5 UI Images. In my Unity hierarchy, the first title is the first transform, etc... But the problem is about the "chevron" shape of this bar title because the first title image has to be in front of the second and the second title in front of the third, etc. With the Unity automatic ordering system I don't know how to fix that.
Hi Crevecoeur.
Elements are renderered from top to bottom. So whatever is first in your Unity editor UI will be rendered first. Items lower in the list will be rendered over the top of the higher up ones.
So in your case can you put the Dark grey chevron with "Well" text as the first item then go in reverse order.
Well
As
Nice
Are
Greys
Answer by Kutulue · Mar 18, 2016 at 05:42 AM
I think you have the SetSiblingIndex variable wrong. SetSiblingIndex(0) will move the element to the top of the Heirachy which will put it behind all other elements. SetSiblingIndex(10000) will force it to the bottom as long as there are not more than 10000 elements in your heirachy. Being at the bottom of the Heirachy will force it to the front of the display.
Your answer
Follow this Question
Related Questions
4.6 C# change canvas dependent on value 0 Answers
Unity 2021 LTS: IPointerEnterHandler is broken 1 Answer
DropDown menu(add item from input field): Object reference not set to instance of an object C# 1 Answer
Cannot accessing text in InputField Array 1 Answer
Changing the target of a button that takes a gameobject as a parameter? 0 Answers