Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

“Attaching” instantiated prefab to a gameobject

Discussion in '2D' started by digital_monk, Oct 24, 2020.

  1. digital_monk

    digital_monk

    Joined:
    Jun 2, 2017
    Posts:
    10
    I have 2 game objects (2D project):

    GameObject enemy1 = GameObject.Find("Enemy1"); // "Order in Layer" 1
    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?