Search code examples
unity-game-enginegameobject

How can I duplicate a gameObject in code Unity


I want to duplicate the gameObject called "Damaged".

enter image description here

I want it to have the exact name, position and to be a child under the gameObject Boss. The whole idea is that every time I call a function, a gameObject should be created, that has an Animator with a single animation, then when the animation is played, there is an event which destroys that gameObject. I tried the obvious Instance solution and I get the object outside the parent class.:

enter image description here

GameObject duplicate = Instantiate(damageText, transform.position, transform.rotation);
animator.SetTrigger("Damage");

Overall, I need help to move the newly created gameObject as a child under the Boss object and trigger the animation for that gameObject. I tried searching it up, but I couldn't find anything.


Solution

  • Set the parent directly after creation and run the animator's Trigger.

    GameObject duplicate = Instantiate(damageText, transform.position, transform.rotation, transform.parent);
    animator.SetTrigger("Damage");
    
    duplicate.GetComponent<Animator>().SetTrigger("Damage");