I have 2 game objects (2D project):
GameObject enemy2 = GameObject.Find("Enemy2"); // "Order in Layer" 2```
A fire prefab is instantiated (just a fire animation):
```GameObject go = Instantiate(Resources.Load<GameObject>("Animations/Fire1")); // "Order in Layer" 5
go.transform.SetParent(enemy1.transform);
go.transform.position = enemy1.transform.position;```
Since the fire prefab's Sprite Renderer's `Order in Layer` is 5, it always on top of both enemies.
I would like the fire to appear above enemy1 but behind enemy2 regardless of what their `Order in Layer` is changed to. Basically, it should look like the enemy is catching fire, even if it moves or if it's layer order changes.
How can this be achieved? I thought making the fire prefab a child of the enemy gameobject (with code) would do it, but it doesn't. Making the fire animation a child of the enemy manually in the editor works perfectly. How do I replicate that with code?
It really should work, so your job is to find out why it does not.
Steps:
-
do it in the editor and see it succeed. Is it succeeding because you truly see layer 1 / 2 / 5 on the specific objects? Or are the layers wrong and it is miraculously okay in the editor.
-
run it in game, and then PAUSE the editor, Now inspect the scene. Do the layers seem the same as in the editor? Does something else seem different? Is it parented where you think? etc.
Also, you can combine the Instantiate AND the parenting into one, which gets you the benefit of not having to worry about positioning and rotating:
Roughly speaking,
GameObject foo = Instantiate<GameObject>(
ResourcesLoadedPrefab, DesiredParentGameObject.transform);
Thanks! Instantiating the prefab in this way fixed the issue:
go = Instantiate(Resources.Load<GameObject>("Animations/Fire1"), enemy1.transform);
Changing the added prefab’s sortingOrder was also necessary to make things working correctly:
go.GetComponent<SpriteRenderer>().sortingOrder = enemy1.GetComponent<SpriteRenderer>().sortingOrder;
After this there was a small issue - the instantiated prefab would randomly appear behind or in front of the enemy. This was fixed by adding a Sorting Group component to the fire prefab - but I’m really not sure why!
Changing the fire’s Sprite Renderer’s Layer order didn’t make any difference, but adding a Sorting Group fixed it immediately. Why is this?
You wrote this:
go.GetComponent<SpriteRenderer>().sortingOrder = enemy1.GetComponent<SpriteRenderer>().sortingOrder;
Don’t you intend to do this and add +1 (or subtract 1)?
Making them the same is why you have randomly sometimes front / behind.
Of course!! Never thought of that! Will try it. Thanks!