- Home /
Question by
ic3t3a2000 · Dec 15, 2012 at 02:44 PM ·
instantiateparentchildcamera.main
Instantiate a game object in array then change parent
I am using a mouse click to instantiate random game objects using an array. But I want these objects to have the parent to be Main Camera. I can't seem to get the transfrom.parent code correct. The objects just spawn as clones with no parent. Below is my code.
var respawnPrefab : GameObject;
var respawnPrefab1 : GameObject;
var respawnPrefab2 : GameObject;
var respawn : GameObject;
//var loopHandle : boolean = true;
var wanttobeparent : GameObject;
function Start()
{
if (respawn==null)
respawn = GameObject.FindWithTag ("Respawn");
}
function Update()
{
var objs = new GameObject[3];
objs[0] = respawnPrefab;
objs[1] = respawnPrefab1;
objs[2] = respawnPrefab2;
if (Input.GetKeyDown (KeyCode.Mouse0))
{
GameObject go = Instantiate(objs[(Random.Range(0, objs.Length))], respawn.transform.position, respawn.transform.rotation) as GameObject;
go.transform.parent = Camera.main.transform;
}
}
Comment
Best Answer
Answer by fafase · Dec 15, 2012 at 02:58 PM
I think you are mixing UnityScript and C#: this is C# or at least I have never seen it for UnityScript and it doe snot work for me:
GameObject go = Instantiate(objs[(Random.Range(0, objs.Length))], respawn.transform.position, respawn.transform.rotation) as GameObject;
This works for me:
var obj = Instantiate(objs[(Random.Range(0, objs.Length))], respawn.transform.position, respawn.transform.rotation);
obj.transform.parent = Camera.main.transform;