- Home /
How do you change a sprite's sorting layer in C#?
Basically I am making a 2D platformer and I have a sprite that is in the foreground and when my player flips a switch, I want the sprite to move to the background. I can do this manually by changing the Sprite Renderer sorting layer, but I can't seem to figure out how to change this in the code, or if it is even possible?
If not, what would be an alternate solution for what I'm trying to do?
Answer by NoseKills · Mar 13, 2014 at 01:57 PM
To add the layer changing to emalbs answer since his example only changed sorting order on the same layer
using UnityEngine;
using System.Collections;
public class SortingOrderScript : MonoBehaviour
{
public const string LAYER_NAME = "TopLayer";
public int sortingOrder = 0;
private SpriteRenderer sprite;
void Start()
{
sprite = GetComponent<SpriteRenderer>();
if (sprite)
{
sprite.sortingOrder = sortingOrder;
sprite.sortingLayerName = LAYER_NAME;
}
}
}
It works for me, i dont know why this cain of samples are not in the unity docs... Thank you again
Answer by emalb · Jan 08, 2014 at 01:47 PM
Have a go at setting your SpriteRenderer's sortingOrder. The following example should enable you to manipulate it in the Inspector as your game runs.
using UnityEngine;
using System.Collections;
public class SortingOrderScript : MonoBehaviour
{
public int sortingOrder = 0;
private SpriteRenderer sprite;
void Start()
{
sprite = GetComponent<SpriteRenderer>();
}
void Update()
{
if (sprite)
sprite.sortingOrder = sortingOrder;
}
}
Just WTF is this not in the documentation?! Thanks for the info, guys. Sorting layers are defined for all Renderers (in the API), if anyone wonders.
Answer by rollrodrig · Sep 06, 2014 at 10:28 PM
Thank you very much !! I was looking for it a lot !!
Answer by koslovdenis · Jun 12, 2017 at 07:09 PM
Heyy guys what about multiple sprites at the same time?
SpriteRenderer[] sprites; //fill this however fits your game
foreach (var sprite in sprites)
{
sprite.sortingOrder = sortingOrder;
sprite.sortingLayerName = LAYER_NA$$anonymous$$E;
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Delayed response: Jumping up from ledge 0 Answers
2d c# boss follow code 0 Answers
Can't move instantiated 2d game oject. 0 Answers