HoloLens and Unity tip #001- Scaling of rotated GameObjects

HoloLens and Unity tip #001- Scaling of rotated GameObjects

When doing scaling of rotated GameObjects in Unity it is very important to understand some things.

The way scaling works is by setting the localScale property of the Transform of the GameObject. The scaling is always relative to the parent. If there is no parent GameObject the scaling is of the object itself. An interesting fact is scaling by removing temporarily the parent. This allows you not to be depend to the scale factor of the parent.

 
    class ObjectScaler : MonoBehaviour
    {
        private Transform parent = null;

        public void ScaleWithoutParent(Vector3 scale)
        {
            // store parent
            parent = gameObject.transform.parent;

            // remove parent from gameobject
            gameObject.transform.parent = null;

            // scale
            gameObject.transform.localScale = scale;

            // set the parent back 
            gameObject.transform.parent = parent;

        }
    }

Another issue you get with scaling is when the GameObject is rotated. Scaling will be approximately based on the amount of rotation. Meaning that you can’t be sure that the scaling is exact every time. If you set the scale of a rotated GameObject from for example the Update() method, the size of the GameObject will differ everytime and causing it to bounce like a heart. If you look closely you will notice that it is always the same range of values.

To resolve this issue you will need to reset to rotation to something we call “no-rotation”. This is achieved by setting the rotation of the GameObject to Quaternion.Identity.

   class ObjectScaler : MonoBehaviour
    {
        private Quaternion prevRotation;

        public void ScaleMyObject(Vector3 scale)
        {
            // store rotation
            prevRotation = gameObject.transform.rotation;

            // reset to no-rotation
            gameObject.transform.rotation = Quaternion.identity;

            // scale
            gameObject.transform.localScale = scale;

            // set rotation
            gameObject.transform.rotation = prevRotation;
        }
    }

A simple code example above. Keep in mind that we do not check if the parent of their parent(s) are rotated. If you use one or more parents (E.g. pivoting a GameObject) you will need to reset their rotation too.

Be aware! if your GameObject has one or more rotated GameObjects in the parent chain you will need to reset their rotation as well. Otherwise you will still experience incorrect values.

 

Leave a Reply