You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity中如何在不改变指定宽高比的前提下对Prefab进行缩放操作

Unity Prefab固定宽高比缩放约束实现方案

核心思路

通过「属性存储脚本+编辑器专属监听脚本」的组合实现,既不引入多余的运行时代码开销,也能保证编辑器下操作时的比例约束生效。

步骤1:编写宽高比属性存储脚本

该脚本直接挂载到需要控制的Prefab根节点,用来存储约束开关、宽高比配置参数:

using UnityEngine;

public class AspectRatioConstraint : MonoBehaviour
{
    public bool enableConstraint = true;
    public AspectRatio presetRatio = AspectRatio.Ratio4_3;
    public float customRatio = 1.333f; // 默认4:3
    
    public enum AspectRatio
    {
        Ratio1_1,
        Ratio4_3,
        Ratio16_9,
        Ratio16_10,
        Custom
    }

    public float GetTargetRatio()
    {
        return presetRatio switch
        {
            AspectRatio.Ratio1_1 => 1f,
            AspectRatio.Ratio4_3 => 4f/3f,
            AspectRatio.Ratio16_9 => 16f/9f,
            AspectRatio.Ratio16_10 => 16f/10f,
            AspectRatio.Custom => customRatio,
            _ => 4f/3f
        };
    }
}

步骤2:编写编辑器缩放监听脚本

将该脚本放在项目的Editor文件夹下(必须,否则无法正常编译),用来监听编辑器下的缩放操作,实时修正比例:

using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(AspectRatioConstraint))]
public class AspectRatioConstraintEditor : Editor
{
    private AspectRatioConstraint _target;
    private Vector3 _prevScale;

    private void OnEnable()
    {
        _target = (AspectRatioConstraint)target;
        _prevScale = _target.transform.localScale;
    }

    private void OnSceneGUI()
    {
        if (!_target.enableConstraint) return;
        
        Vector3 currentScale = _target.transform.localScale;
        // 检测缩放是否发生变化
        if (currentScale != _prevScale)
        {
            float targetRatio = _target.GetTargetRatio();
            // 判断用户修改的是X轴还是Y轴,以修改的轴为基准修正另一个轴
            if (!Mathf.Approximately(currentScale.x, _prevScale.x))
            {
                currentScale.y = currentScale.x / targetRatio;
            }
            else if (!Mathf.Approximately(currentScale.y, _prevScale.y))
            {
                currentScale.x = currentScale.y * targetRatio;
            }
            _target.transform.localScale = currentScale;
            _prevScale = currentScale;
        }
    }
}

操作使用方法

  • 将AspectRatioConstraint脚本挂载到你的Prefab根节点
  • 在Inspector面板勾选enableConstraint启用约束,选择对应的预设宽高比,也可以选择Custom自定义你需要的比例值
  • 之后在Scene视图拖拽缩放、或者直接修改Inspector面板的缩放参数时,物体会自动按照设定的宽高比同步另一个轴的数值,保证比例不会失调

额外适配说明

  • 如果是需要约束UI元素的宽高(而非缩放值),只需要将Editor脚本里的localScale替换为GetComponent<RectTransform>().sizeDelta即可
  • 如果是3D物体需要约束XYZ三个轴的比例,只需要扩展枚举项和计算逻辑,加入Z轴的适配规则即可

提示:该约束仅在编辑器下操作时生效,运行时如果需要动态约束比例,直接调用GetTargetRatio()方法自行适配即可

内容的提问来源于stack exchange,提问作者Ameer Hamza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 12:36:04