- Home /
Adding ChildObject
Hi guys I've got a problem. I've got some Items that i can add to the scene with a script that works well. But I want all the items with the Tag "Item" to be a childObject of a gameobject in the scene. This code is on the gameObject which has to be on the..."FatherObject" of the Items. My code so far:
var Items:GameObject [] ;
function Update () { Items = GameObject.FindGameObjectsWithTag("Item");
//if i add them until now they will be added... everything works fine
Items = gameObject.AddComponent("GameObject");
// But now it says Cannot convert 'UnityEngine.Component' to 'UnityEngine.GameObject[]'.
}
ohh i forgot something thanks for the answers now it works
var Items :GameObject []; function Update () { Items = GameObject.FindGameObjectsWithTag("Item"); for(var blah : GameObject in Items){ blah.transform.parent = transform ; } }
Answer by tomekkie2 · Jan 01, 2012 at 05:35 PM
You just should use:
for (var item in Items) {
item.transform.parent = transform;
}
Answer by aldonaletto · Jan 01, 2012 at 05:42 PM
AddComponent is used to add Rigidbody, Collider, scripts etc. to an object; to child some object to another, set its transform.parent property to the parent's transform:
... var items = GameObject.FindGameObjectsWithTag("Item"); for (var obj in items){ obj.transform.parent = transform; }This will make the object owner of this script the parent of all Item tagged objects.
But don't do it at Update, or your game will crawl like a wounded snail! Place this code at Start, or in a function that you call only when desperately needed.
EDITED: But the best way to child a instantiated object to something is right after the creation:
var prefab: GameObject; var daddy: Transform; // drag here the parent object ... // when instantiating the object: var obj: GameObject = Instantiate(prefab, ...); obj.transform.parent = daddy; // or transform, if this object is the parent