"Attaching" instantiated prefab to a gameobject

Viewed 57

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 Answers

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.

Related