Programmatically Ordering Game Objects in 2d / Hierarchy
Hi,
I'm new to Unity (and really enjoying the learning curve) and to these forums. I have 15 or so years of experience programming 2d games in other packages, before switching to Unity recently. I've looked all over for a definitive answer to how best to handle the 2d visual sorting of nested game objects, but I'm stumped as to what the best approach is. What I have so far feels like a messy hack compared to how I would have previously done this.
I generally like working almost entirely in code, so I'm looking to do this programmatically.
For the sake of an example, say we have a project that contains several sorting layers (BackgroundLayer, CharacterLayer and MenuLayer) and we want to add a several characters to the character layer and each character has multiple, nested "parts" (head, body, arms, legs) that need to sit inside the character and be accessed independently and potentially have their sorting order (or what I would call "Z-index") within their parent game object manipulated via code.
I understand completely that if I want to change the sorting order of all the characters within their sorting layer, I can do that easily via script by using the following:
characterA.GetComponent<SpriteRenderer>().sortingOrder = 3;
The above would place character A at a Z-index of 3 within the layer, giving us the ability to send other objects in the character layer behind our character if we wanted.
What I don't understand is how to do the same thing with nested game objects / sprites that sit inside our character game object. If I have 10 characters on the screen and each one has arms, legs and so on, it would surely be absurd to programatically try and keep track of every one of those game objects and assign them a sorting order in relation to all the other characters' arms / legs.
I have set up my character already, by adding all the "pieces" programatically and assigning my character game object as the parent of each "piece".
But I just can't figure out how each piece can be moved "up" or "down" in the sorting hierarchy via code.
I've seen information about 2d sorting (https://docs.unity3d.com/Manual/2DSorting.html) and about setting sibling index (https://docs.unity3d.com/ScriptReference/Transform.SetSiblingIndex.html) but I couldn't figure out the best way to approach what I'd like to do from either of them.
I hope that makes sense!! Apologies for the rambling message!!
Thanks in advance for any help.
Ian
Your answer
Follow this Question
Related Questions
How to sort Animations and Controllers? 1 Answer
GameObject can be seen through panel inside a canvas. 1 Answer
[UNET] Having problems with clients not being able to shoot after they reload 0 Answers
Animation help / possibly a bug,Help needed with animation. Bug? 2 Answers
How do you selectively mask objects based on what side they are on? 0 Answers