- Home /
How do make a Instantiated prefab a child of exsisting Object?
OK so i just watched quill18's destruction tutorial. he came up with this script. which pretty much says when A collides with B. B gets destroyed and replaced with C. This works perfectly if the object(C) you are instantiating is not meant to move, but in my case I need the object(C) to be parented to an other object(D), which is moving, so that object(C) moves with the moving object(D). however i am not sure how to do this. Please help?
using UnityEngine; using System.Collections;
public class Destrutiable : MonoBehaviour {
public GameObject debrisPrefab;
public Transform DT;
void Start () {
}
void OnCollisionEnter( Collision collision)
{
if(collision.impactForceSum.magnitude > 20f)
{
DestroyMe();
}
}
void DestroyMe()
{
if(debrisPrefab)
{
Instantiate(debrisPrefab, transform.position, DT.rotation);
}
Destroy(gameObject);
}
}
Answer by Berenger · Jan 07, 2015 at 08:17 AM
The instantiate function will return the newly created instance. Put it in a var (it's a gameobject, will need a cast though) thhen assign it's parent.
Answer by Juice-Tin · Jan 07, 2015 at 08:32 AM
http://docs.unity3d.com/ScriptReference/Transform.SetParent.html
ObjectC.SetParent(ObjectD, true);
Try somethin like that.
SetParent is a method of the Transform component. Read the documentation carefully.
Answer by nightowl79a · Jan 07, 2015 at 01:19 PM
You can do something like this:
GameObject go = Instantiate (exsample, transform.position, Quaternion.identity) as GameObject;
go.transform.parent = transform;
You Instantiate the new game object and put it in a new game object variable. Then just parrent it like you would any other game object.