I have a number of cloned objects from an Instantiate() and at runtime they all appear in the root of the hierarchy. Is there a quick way to get them to appear as children instead?
This is simply for aesthetics and ease of debugging.
edit:
Thanks insominix and flaviusxvii, you both gave the correct answer. I was just having trouble seeing it because of my poorly thought out Spot class. I now have refactored the class.
Don’t think so. The best you can do is to set transform.parent but it will create transformation headaches. You can create some empty “clones container” object as root and assign it as parent of clones to clean up.
Yes. All you need to do is set their parent to the Transform you want them to be under. So something like this:
Transform instance = (Transform)GameObject.Instantiate(objectToClone);
instance.parent = newParentObject.transform;
You just need a way to get which object you want to parent it to. You could either get it from a property in your class script or even find it by tag (useful for prefabs).
*Edit
I just tried out a simple example with no problem:
using UnityEngine;
using System.Collections;
public class TestReparent : MonoBehaviour {
public Transform newParent;
void Start () {
GameObject newObject = new GameObject();
newObject.transform.parent = newParent;
}
}
I use a few global gameobjects with zeroed out transforms for the purpose of keeping the hierarchy tidy.
// This is in my weapon script.. it makes the container object for all ordinance.
_ordinanceParent = GameObject.Find("OrdinanceParent");
if(!_ordinanceParent) {
_ordinanceParent = new GameObject("OrdinanceParent");
}
// Later on when the weapon fires I put the new ordinance gameobject in the container..
GameObject s = Instantiate(ordinance, emitWorldSpace, transform.rotation) as GameObject;
s.transform.parent = _ordinanceParent.transform;
Hope this helps.