- Home /
Instantiate a prefab as a child of an existing object?
Hey everyone! I'm working a 3D VR escape the room game. The player goes through the room opening drawers to find the randomly spawned objects. The objects have to be parented to the animated drawers for everything to work correctly. I wrote some code to randomly spawn the items in one of three locations from an array of spawn points, but I don't know how to spawn them as children of the drawers. Any help you can offer is greatly appreciated! Thank you! Here's my code:
public Transform[] wrenchPoints;
public Transform[] hammerPoints;
public Transform[] knifePoints;
public GameObject wrench;
public GameObject hammer;
public GameObject knife;
// Use this for initialization
void Start () {
SpawnHammer ();
SpawnWrench ();
SpawnKnife ();
}
// Update is called once per frame
void Update () {
}
void SpawnHammer()
{
Debug.Log ("Spawning Hammer");
int hammerSpawnIndex = Random.Range (0, hammerPoints.Length);
Instantiate (hammer, hammerPoints [hammerSpawnIndex].position, hammerPoints [hammerSpawnIndex].rotation);
Debug.Log(hammerPoints[hammerSpawnIndex]);
}
void SpawnWrench()
{
Debug.Log ("Spawning Wrench");
int wrenchSpawnIndex = Random.Range (0, wrenchPoints.Length);
Instantiate (wrench, wrenchPoints [wrenchSpawnIndex].position, wrenchPoints [wrenchSpawnIndex].rotation);
Debug.Log(wrenchPoints[wrenchSpawnIndex]);
}
void SpawnKnife()
{
Debug.Log ("Spawning Knife");
int knifeSpawnIndex = Random.Range (0, knifePoints.Length);
Instantiate (knife, knifePoints [knifeSpawnIndex].position, wrenchPoints [knifeSpawnIndex].rotation);
Debug.Log(knifePoints[knifeSpawnIndex]);
}
Doing this from memory but basicly.
using UnityEngine;
using System.Collections;
public class InstantiateTHing : $$anonymous$$onoBehaviour {
public GameObject prefab;
// Update is called once per frame
void Update () {
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.Space))
{
GameObject go = Instantiate(prefab, transform.position, Quaternion.identity) as GameObject;
transform.parent = go.transform;
}
}
}
Answer by Munchy2007 · May 04, 2016 at 11:06 AM
You should use transform.SetParent :-
GameObject knife;
GameObject drawerGO;
knife.transform.SetParent(drawerGO.transform, false);
If you use true for the 2nd parameter the childed object will keep it's current world position, otherwise it will be positioned relative to the new parent, based on the prefab local position value.
Your answer
Follow this Question
Related Questions
Spawning prefabs dependant upon Health UI? 2 Answers
Instantiate is throwing my throwing my objects? 1 Answer
Distribute terrain in zones 3 Answers
Instantiating at different rates 1 Answer
Player 2 not spawning 1 Answer