Child object reset to parent transform?

In the editor it is easy to reset a child object's transform so that it matches the parent's but is there an easy way to do this in code? I am using the long way:

transform.rotation = parent.transform.rotation;
transform.localPosition = Vector3(0,0,0);
transform.localScale = Vector3(1,1,1);

Is there a shorter (one line) way?

more ▼

asked Jan 28, 2011 at 08:50 AM

avatar image

545 68 51 55

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

Another little improvement ;)

    transform.localRotation = Quaternion.identity;
    transform.localPosition = Vector3.zero;
    transform.localScale = Vector3.one;

both Transform.rotation and Transform.position are special properties that automatically convert the world position into local position. That's why it's better to set the local position or rotation at least in such a case.

There is no way to set the global scale. Unity just offers a readonly lossyScale to get the resulting scale in world space. (Setting the scale in world space would be a pain to transform the scale through all parents (rotation, position, scale) and would be prone to fail due to inaccuracy of floating point values

more ▼

answered Jan 28, 2011 at 12:02 PM

avatar image

96.8k 53 297 526

(comments are locked)
10|3000 characters needed characters left

No, I think your 3 line-way is already pretty much the best you can do. I could think of one potential little improvement:

transform.rotation = parent.transform.rotation;
transform.localPosition = Vector3.zero;
transform.localScale = Vector3.one;

As Vector3 is a struct this probably won't really make much of a difference as structs are by value and not by reference (if it was a by-reference type this would spare you two objects which later might have to be garbage collected). Nevertheless, I think it's good programming practice to use such "standard objects" for "standard cases".

more ▼

answered Jan 28, 2011 at 09:35 AM

avatar image

12.3k 51 152 230

Thanks for the tips. Just seemed odd that something so easy to do in the editor wasn't equally easy in code and thought I must be missing something.

Jan 29, 2011 at 08:20 AM Ben
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here



Answers and Comments



asked: Jan 28, 2011 at 08:50 AM

Seen: 8382 times

Last Updated: Jan 28, 2011 at 08:50 AM