- Home /
How can I Instantiate a clone as a child of another object, and inherit the parent object's scale?
I currently have a Laser/Mirror puzzle that relies on cloning laser objects to simulate the bouncing of light off of mirrors. The way that this is being done is with a call to Instantiate of an object that is already contained in the hierarchy of the "laser projector" object.
However, the laser projector object has a scale factor set that I need to be applied to the newly cloned object which should then be added as a child of the projector. There are a couple of ways I can do this that I know of. I can either traverse the hierarchy and multiply the scale factors together, since I know how high the hierarchy is and it won't change. I could also hard code the scaling factor into the clone, since I know what is, however it may change and that isn't very modular.
I would really like to just be able to instantiate the new laser as a child of the projector and have it receive the scaling factors through the hierarchy though. I can't find a clean way to do this in the documentation, and it seems like the only way to parent something is to set its transform.parent after the object has already been made and added to the root of the scene hierarchy. This means that when the parent of it is eventually set, there's no way that the nested scaling factors will be transferred to the new lasers.
Is there a nice way to do what I'm trying to do?
Thanks.
Answer by duck · Apr 30, 2010 at 08:02 AM
After you have set the object's transform.parent, set it's Transform.localScale to 1, 1, 1:
newInstance.transform.parent = parentTransform;
newInstance.transform.localScale = Vector3.one;
Because it has a local scale of 1 in all axes, its size will directly reflect its parent scale transformation.
i have someting like this:
for (int i = $$anonymous$$Clones; i < maxClones; i++) { Instantiate(master, RandomPosition(), Quaternion.identity);
}
master is a prefab... how do i make it child of the transform?
Please no new questions inside answers, especially if they are only marginally related.
Store your instantiated object in a local variable (C# example):
GameObject newObj=Instantiate(.....) as GameObject;
newObj.transform.parent=transform;
Answer by Cjj · Jul 09, 2010 at 04:46 PM
Use Object.Instantiate(). http://unity3d.com/support/documentation/ScriptReference/Object.Instantiate.html