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?
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;
}
}