- Home /
Instantiate object as child of exsisitng game object
Im trying to test the created level in another scene but need to use DontDestoryOnLoad in awake function. How do I instantiate my new objects as a child of an exsisting game Object?
//#pragma strict import System.Collections.Generic;
var BlockPositions : List.<Vector3> = new List.<Vector3>();
var collide : boolean = false;
var endCube = gameObject;
var prefab = gameObject;
var testPlayer : boolean = false;
function Awake(){
//DontDestoryOnLoad();
}
function OnCollisionEnter(coll: Collision){ //Colliding with object?
if(coll.gameObject.tag=="floor"){
collide=true;
}
}
function OnCollisionExit(coll: Collision){
collide=false;
}
function Update () {
myPosition = transform.position;
if(Input.GetButtonDown("up")){
transform.position.y = transform.position.y+1;
if (collide == false){
collide = true;
}
}
if(Input.GetButtonDown("down")){
transform.position.y = transform.position.y-1;
if (collide == false ){
collide = true;
}
}
if(Input.GetButtonDown("left")){
transform.position.x = transform.position.x-1;
if (collide == false){
collide = true;
}
}
if(Input.GetButtonDown("right")){
transform.position.x = transform.position.x+1;
if (collide == false){
collide = true;
}
}
if (Input.GetButtonDown ("Submit")){
if (BlockPositions.Contains(transform.position))
{
// DestroyImmediate(prefab);
testPlayer = true;
Instantiate(endCube, transform.position, Quaternion.identity);
BlockPositions.Add(transform.position);
testLevel();
/*
NOW GIVE USER GUI OPTION TO RETRY LEVEL/SUBMIT LEVEL
*/
}
}
Debug.Log(myPosition);
if (collide == false){
collide = true;
Instantiate(prefab, transform.position, Quaternion.identity);
BlockPositions.Add(transform.position);
}
}
function testLevel(){
WaitForSeconds(2);
Application.LoadLevel("TestLevel");
}
Answer by Cherno · Jun 08, 2015 at 11:08 AM
You can't do it. However, what you can do is instantiate it normally, and immediately afterwards set it's parent to whatevery GameObject's transform you want.
gameObject parentObject;
Instantiate(endCube, transform.position, Quaternion.identity);
endCube.transform.parent = parentObject.transform;
Answer by JparrishAU · May 14, 2019 at 05:30 PM
Just FYI. You can do this directly now using the overloaded Instantiate method.
Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);
Your answer
Follow this Question
Related Questions
Renaming Child Objects during Instantiate? 1 Answer
Instantiated GameObject gets spawned as a child 2 Answers
Instantiate prefab as Child to remove and re-do later 2 Answers
Creating new Transform from existing objects Transform to Instantiate object 1 Answer
Instantiated GameObject collision without script repetition? 1 Answer