Unity C#如何维持3D对象宽高比并按选定比例缩放
Unity 3D对象宽高比自动适配实现方案
功能说明
- 仅修改目标GameObject的
localScale的X、Y属性,忽略Z轴缩放值,不影响对象深度表现 - 可通过枚举选择预设宽高比,自动计算适配后的缩放值
- 同时支持编辑态和运行时生效,在Inspector切换参数后立即更新对象尺寸
预设宽高比枚举定义
public enum ImmersiveAdAspectRatioSize { EighteenBySix = 0, // 18:6 SixteenByNine = 1, // 16:9 FourByThree = 2, // 4:3 ThreeByTwo = 3, // 3:2 OneByOne = 4, // 1:1 }
完整适配脚本代码
using UnityEngine; [ExecuteAlways] // 支持编辑态实时运行 public class AspectRatioFitter3D : MonoBehaviour { [Header("宽高比配置")] public ImmersiveAdAspectRatioSize targetAspectRatio; [Tooltip("适配基准:勾选则以当前高度为基准调整宽度,取消则以当前宽度为基准调整高度")] public bool fitByHeight = true; private Transform _selfTransform; private void Awake() { _selfTransform = transform; UpdateScale(); } // 编辑态修改参数时自动触发校验更新 private void OnValidate() { if (_selfTransform == null) { _selfTransform = transform; } UpdateScale(); } // 运行时启动自动适配 private void Start() { UpdateScale(); } // 计算并更新对象缩放 private void UpdateScale() { float targetRatio = GetAspectRatioValue(targetAspectRatio); Vector3 currentScale = _selfTransform.localScale; float newX = currentScale.x; float newY = currentScale.y; if (fitByHeight) { // 高度不变,按比例计算宽度 newX = currentScale.y * targetRatio; } else { // 宽度不变,按比例计算高度 newY = currentScale.x / targetRatio; } // 仅修改X、Y轴,保留原始Z轴缩放值 _selfTransform.localScale = new Vector3(newX, newY, currentScale.z); } // 枚举值转对应宽高比数值 private float GetAspectRatioValue(ImmersiveAdAspectRatioSize ratioType) { return ratioType switch { ImmersiveAdAspectRatioSize.EighteenBySix => 18f / 6f, ImmersiveAdAspectRatioSize.SixteenByNine => 16f / 9f, ImmersiveAdAspectRatioSize.FourByThree => 4f / 3f, ImmersiveAdAspectRatioSize.ThreeByTwo => 3f / 2f, ImmersiveAdAspectRatioSize.OneByOne => 1f, _ => 16f / 9f // 异常场景默认返回16:9比例 }; } }
使用说明
- 将
AspectRatioFitter3D脚本挂载到需要调整宽高比的3D对象上 - 选择适配基准:勾选
fitByHeight则保持当前高度不变,自动计算调整宽度;取消勾选则保持当前宽度不变,自动调整高度 - 在
targetAspectRatio下拉框中选择需要的目标宽高比,对象会自动更新缩放尺寸
内容的提问来源于stack exchange,提问作者Wajid Ali
相关产品推荐
相关产品推荐

