Auto Increase SpriteRenderer Order in Layer?

Hi everyone!

I have 2D project in Unity 5. I have a simple gameobject with a spriteRenderer component.

When you instantiate object its SpriteRenderer’s default Order in Layer is zero. I want this: When a new object is instantiated its Order in Layer is set to higher than other objects in the scene.

I made a simple script:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

[ExecuteInEditMode]
public class LayerScript : MonoBehaviour {
	private static int nextHighestOrder = 0;
	
	// Use this for initialization
	void Start () {
		UpdateOrder ();
	}
	void UpdateOrder() {
		var myRenderer = GetComponent<SpriteRenderer> ();

		if (myRenderer.sortingOrder == 0) {
			// This is a new object
			myRenderer.sortingOrder = nextHighestOrder;		
			nextHighestOrder++;
		} else {
			// Order has already been assigned to this object, skip
			return;
		}

	}
	
	// Update is called once per frame
	void Update () {
	
	}
}

This script works fine until I close the scene and reopen it. When reopening the scene, some objects have changed the Order in Layer value.

Why does the order of the objects change? Thanks for the help!

(question is 7 years old, but for people stumbling on the same issue…)

You probably need to Undo.RecordObject objects modified by your custom script. Generally speaking, whenever you modify properties by code (not using a property drawer, which already handles it), you want to Undo Record the affected object (here, the SpriteRenderer component). This will enable both Undo, mark dirty and therefore allow saving changes.

A quick way to test it is to Undo (Ctrl+Z) the changes. If Undo doesn’t work and undoes the action done before that one, chances are that it will also not save properly.

There is also the fact that nextHighestOrder is static and so after restarting the editor you will restart it from 0, but it doesn’t seem to be your specific issue in this question.
Example code:

Undo.RecordObject(myRenderer, "Set sorting order");
myRenderer.sortingOrder = nextHighestOrder;