Home > Software design >  How to scale something in unity without changing the aspect ratio?
How to scale something in unity without changing the aspect ratio?

Time:11-02

I am trying to restrict a user in unity editor that if the user stretch my given prefeb the object will scale up and down according to the selected aspect ratio in the inspector. Like if the user selects 4:3 and scale that object it will change according to the aspect ratio. Kindly help me in that.

CodePudding user response:

From the center of the scale handle, al the scales in the 3 axis are changed at once:

enter image description here

So if you set a escale for example of (4,3,0) and handle the scel handle from its centre, the proportion is preserved. You can check for example in a quad, how it changes from 4,3,0 to 8,6,0 and so on, increasing or decreasing.

If you are doing that with code, you can arrange that whenever you change the scale of an axis of interest, you calculate and set the scale of the other axis so that the relation 4:3 is maintained.

CodePudding user response:

[ExecuteInEditMode]
public class AspectScale : MonoBehaviour
{
    private Vector3 _baseScale;
    private Vector3 _current;
    private Transform _transform;

    private void OnEnable ()
    {
        _transform = transform;
        _baseScale = _transform.localScale;
        _current = _baseScale;
    }

    private void Update ()
    {
        if (_transform.hasChanged)
        {
            if (_current.x != _transform.localScale.x)
                SetScale(_transform.localScale.x/_baseScale.x);
            else if (_current.y != _transform.localScale.y)
                SetScale(_transform.localScale.y/_baseScale.y);
            else if (_current.z != _transform.localScale.z)
                SetScale(_transform.localScale.z/_baseScale.z);
        }
    }

    private void SetScale (float value)
    {
        _transform.localScale = _baseScale*value;
        _current = _transform.localScale;
    }
}

Disable for change aspect.

  • Related