repinSlun
repinSlun

Reputation: 99

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.

Upvotes: 0

Views: 514

Answers (2)

KiynL
KiynL

Reputation: 4266

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");

Upvotes: 0

Titoine
Titoine

Reputation: 11

If you change your Instanciate to add parent transform it should work, instanciate can take parent transform as parameter just add it after like this :

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

If you want to get parent transform you can either find it with its name Like so : Transform bossTransform = GameObject.Find("name").tranform; or you can add it as a public component to your script : public Transform bossTransform;

Upvotes: 0

Related Questions