0
votes

I have 2 game objects (2D project):

GameObject enemy1 = GameObject.Find("Enemy1"); // Sprite Renderer "Order in Layer" 1
GameObject enemy2 = GameObject.Find("Enemy2"); // Sprite Renderer "Order in Layer" 2

A fire prefab is instantiated (just a fire animation):

GameObject go = Instantiate(Resources.Load<GameObject>("Animations/Fire1")); // Sprite Renderer "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 would do it, but it doesn't.

Edit: Making the fire animation a child of the enemy manually in the editor works perfectly. How do I replicate that with code?

1
obvious but, if you want fire to appear above enemy1 but behind enemy2, set the layers of the 3 elements accordingly. For example, enemy1 layer1, explosion layer2, and enemy2 layer3. That does not work?rustyBucketBay
That will work... but I will have many more enemies later. How should the layering be re-arranged when enemy6 catches fire?Yeti
I am not very much into 2D development, but if that works, if the layer 1 is working for the under fire enemies, you can handle in the code the 'underFire' status, and set to that layer all the enemies that are actually under fire. Can you?rustyBucketBay
Actually I don't want to be dealing with the layer ordering at all. If I manually drag the animation and make it a child of the enemy, it works perfectly! I want to replicate that with code.Yeti

1 Answers

0
votes

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.