Question by
virtmar3 · Oct 12, 2015 at 09:49 AM ·
editoreditor-scriptingobjectsspriterenderer
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!
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612041009im_/https://answers.unity.com/themes/thub/images/avi.jpg)