Changing prefab instances from editor script

I need to sort sprites in editor. So i wrote a simply script, that sorts SpriteRenderer.sortigOrder. It works fine for objects, but it does not work for prefab instances. The problem is, that if i change Order in layer via editor, it works fine and the adjusted field is drawn bold.

But if i doing the same thing from my code Order in Layer will be resetet at game starts. Is it a bug? I found that such changes are not displayed bold in editor.

The code is nothing special, just setting sortingOrder by position.

            List<Transform> children = transform.Cast<Transform>().Where(child => child.gameObject.activeInHierarchy).ToList();
            children = children.OrderBy(t => t.position.y).ThenByDescending(t => t.position.x).ToList();

           int z = 0;
           foreach (var child in children) {
               SpriteRenderer r = child.GetComponent<SpriteRenderer>();
                r.sortingOrder = z;
                z += Z_step;
            }

To make thing clear:

  1. I am making changes not from play mode.
  2. Just apply prefab is not an option, since i want multiple blocks using same prefab with overriden Order In Layer. As far as i know, that absolute legal use of prefab instances.

How do i get it?

solved:

PrefabUtility.RecordPrefabInstancePropertyModifications(r);
4 Likes

Thanks for posting the solution to this! Helped me with a similar issue.

1 Like