Instatiate a gameobject/prefab on the parent's current location if the child is destroyed.
So lets say I have parent and a child object, and the moment you destroy the child object how would i instatiate and object on the parent object that would also be destroyed. I know if you do something like this you destroy the object
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.tag == "Child Object")
{
Destroy(collision.gameObject); // for the child object
Instantiate(newObject, transform.position, transform.rotation);
// This works and I can Instantiate a new gameobject in its current position while destroying the old one.
Destroy(GameObject.FindWithTag("ParentObject")); // for the parent object
Instantiate(newOtherObject, transform.position, transform.rotation);
// This DOES NOT works and I cant Instantiate a new gameobject in its current destroyed place- BUT WILL APPEAR in the child's object place of origin where it was destroyed.
}
}
So how would I be able to do that, I know how to instantiate a new object when the Child is destroyed, but I would I really like to know is when I destroy the parent object for it to be able to instantiate a new object in its place in the same location that it was destroyed in? I would like to call it up by the FindWithTag if possible, if not any help to do it another way is also welcomed.
Thanks again.
Answer by v-ercart · Oct 03, 2018 at 07:25 PM
What object is the code you posted running on?
If this is running on a third object (not the child or the parent), I would expect it to work. Both child and parent get created at the location of the third object, which might not be what you want. It would work like this:
If this code is running on a bulldozer, when it hits a "truck trailer" (the child object), it destroys the truck trailer, and spawns "Scrap metal" under the bulldozer. Then it destroys the "Truck" (parent) and creates "engine parts" under the bulldozer.
You might instead want something like this:
Instantiate(newObject, collision.gameObject.transform.position, collision.gameObject.transform.rotation);
Which creates the new object at the location of the child object.
Or maybe you want this:
GameObject parentObject = GameObject.FindWithTag("ParentObject")
Instantiate(newOtherObject, parentObject .transform.position, parentObject .transform.rotation);
Which spawns the new object at the location of the parent object.
(Not what you asked, but if you want to keep that position around, say for example, to play an explosion FX and have the second thing spawn an instant later, you will need to cache that position like this: Transform parentDiedSpot = parentObject.transform; )