有趣的是,此属性无处记录。我什至在ImageEditor 和GraphcisEditor 的源代码中都没有找到它,所以现在我对实际负责显示该字段的内容很感兴趣^^
然而,我发现在对尺寸设置进行更改后,编辑会调用EditorUtility.SetDirty(graphic);。当然,这在构建中不可用,但它让我寻找 - 我认为 - 正确的解决方案:
更改属性后,您必须致电SetVerticesDirty
gridImage.SetVerticesDirty();
或者干脆SetAllDirty
gridImage.SetAllDirty();
虽然我不确定效率.. 你可能应该只在值实际改变时才调用它。
还要避免所有那些重复的GetComponent 电话!在Awake 中执行一次,然后重新使用引用。
你的Lerp终于没用了!由于您获得了当前大小并在该大小上计算了所需的大小,因此根本不会进行平滑缩放。而是在类中使用全局字段并更新该字段:
// would even be better if you can already reference this in the Inspector
[SerializeField] private Camera _camera;
public Image gridImage;
public float minSize;
public float maxSize;
private float desiredSize;
private void Awake()
{
if (!_camera) _camera = GetComponent<Camera>();
// initialize the desired size with the current one
desiredSize = Mathf.Clamp(_camera.orthographicSize, minSize, maxSize);
// do it once on game start
UpdateImage(desiredSize);
}
// Update is called once per frame
private void Update()
{
var currentSize = _camera.orthographicSize;
desiredSize -= Input.mouseScrollDelta.y * 3;
//Clamp between min and max
desiredSize = Mathf.Clamp(desiredSize, minSize, maxSize);
// is the scaling already done?
// -> Skip unnecessary changes/updates
if (Mathf.Approximately(desiredSize, currentSize)) return;
//Smoothly interpolates to desired size
_camera.orthographicSize = Mathf.Lerp(currentSize, desiredSize, 5f * Time.deltaTime);
UpdateImage(_camera.orthographicSize);
}
private void UpdateImage(float size)
{
//Change pixels per unit multiplier to half of camera's size (with only 1 decimal char)
gridImage.pixelsPerUnitMultiplier = Mathf.Round(size / 2 * 10f) / 10f;
gridImage.SetVerticesDirty();
}
固定版本:
“动画”末尾的这种轻微抖动来自您在分配 pixelsPerUnitMultiplier 时的舍入,您可能要考虑删除此舍入并简单地应用
gridImage.pixelsPerUnitMultiplier = size / 2f