- Home /
How to instantiate gameobject as a child without scaling
Hi,
I tried to instantiate a gameobject and registerd as some object's child. My code is like below. As you can see I'm always store localscale value before registering as a child because localscale is changed after registering. My code is working but it's a little troublesome because it is my basic method in my application.
Does anyone know other better method?
var someObj = Instantiate(Resources.Load(prefabName)) as GameObject;
var localScale = someObj.transform.localScale;
someObj.transform.parent = transform; // someObj.transform.localScale is changed!
someObj.transform.localScale = localScale;
thanks,
Answer by Dover8 · Nov 26, 2013 at 11:57 AM
This is how localScale works, it gives you the scale in relation to the parent object. If you remove/comment your last line then the object will be parented and still be the same size it was before parenting, but the localScale will be it's scale in relation to the parent.
The best method for instantiating prefabs is to make sure that the prefab root has a scale of (1,1,1) in respect to the parent object that you will instantiate it to. Even if you make an empty game object in the editor to be (1,1,1) as the child, and then make this as the parent of your prefab and apply this as your new prefab. Then at run time you know that you can instantiate and call:
somObj.transform.localScale = Vector3.one;
Right, if you need deeper hierarchies it'S best to build those hierarchies with empty gameobjects and just add the actual objects as child. The "visual" objects can be scaled as you which but the hierarchy isn't affected.
Thank you for your comments. I understand the manner of localScalie. But I have actually have some cases which I want to force child's gameObject to set its original size. In such cases, I prepared function like below.
var localScale = child.transform.localScale; // store original localScale value
child.transform.parent = parent;
child.transform.localScale = localScale; // force set
But that specifically does not keep it's original size, it scales it based on the parent as @Dover8 mentions. If you don't put that last line, it will retain it's original size presu$$anonymous$$g it's parents have uniform scaling if they do not, all sorts of weirdness may ensue.
Your answer
Follow this Question
Related Questions
Unity takes Forever (15 minutes) to apply inspector settings 0 Answers
Change controls to vehicle controls script? 0 Answers
scaling (Resizing) orthographic camera in 2D mode 3 Answers
Stop a enemy by pointing a light at it. 4 Answers
Limit rotate object? 1 Answer