如何让视口一直在中间/居中?现在它在左边

问题描述 投票:0回答:1

不确定该怎么做以及我应该通过代码还是在编辑器中完成。

我可以将视口拖到红色上,并或多或少地手动将其放在中间。但我希望它在中心是自动的。

这个截图是用鼠标拖动红色后的: 这就是我一直希望的样子。

这是内容对象设置的截图:

问题是位于 HorizontalScrollView 上的脚本:

using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class ChiScrollRect : ScrollRect, IPointerEnterHandler, IPointerExitHandler
{
    private static string mouseScrollWheelAxis = "Mouse ScrollWheel";
    private bool swallowMouseWheelScrolls = true;
    private bool isMouseOver = false;

    public void OnPointerEnter(PointerEventData eventData)
    {
        isMouseOver = true;
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        isMouseOver = false;
    }

    private void Update()
    {
        // Detect the mouse wheel and generate a scroll. This fixes the issue where Unity will prevent our ScrollRect
        // from receiving any mouse wheel messages if the mouse is over a raycast target (such as a button).
        if (isMouseOver && IsMouseWheelRolling())
        {
            var delta = UnityEngine.Input.GetAxis(mouseScrollWheelAxis);

            PointerEventData pointerData = new PointerEventData(EventSystem.current);
            pointerData.scrollDelta = new Vector2(0f, delta);

            swallowMouseWheelScrolls = false;
            OnScroll(pointerData);
            swallowMouseWheelScrolls = true;
        }
    }

    public override void OnScroll(PointerEventData data)
    {
        if (IsMouseWheelRolling() && swallowMouseWheelScrolls)
        {
            // Eat the scroll so that we don't get a double scroll when the mouse is over an image
        }
        else
        {
            // Amplify the mousewheel so that it matches the scroll sensitivity.
            if (data.scrollDelta.y < -Mathf.Epsilon)
                data.scrollDelta = new Vector2(0f, -scrollSensitivity);
            else if (data.scrollDelta.y > Mathf.Epsilon)
                data.scrollDelta = new Vector2(0f, scrollSensitivity);

            base.OnScroll(data);
        }
    }

    private static bool IsMouseWheelRolling()
    {
        return UnityEngine.Input.GetAxis(mouseScrollWheelAxis) != 0;
    }
}

我从这个答案中拿走了那个脚本:

https://forum.unity.com/threads/scroll-view-does-not-scroll-with-mousewheel-when-mouse-is-over-a-button-inside-the-scroll-view.848848/

原因是因为问题:当鼠标悬停在滚动视图内的按钮上时,滚动视图不会使用 MouseWheel 滚动。

但是这个脚本也阻止了将视口更改为中心,即使我通过按住 alt 键并选择中心方块将视口的锚点预设更改为中间/中心。

所以我被困在这里了

c# unity3d
1个回答
0
投票

按下矩形变换按钮,看起来像目标的那个

按住 alt 或 shift 或两者,具体取决于您是否要设置锚点,以及缩放以填充。按中间选项(中心)。这会将您的对象对齐到其父矩形的中心。

© www.soinside.com 2019 - 2024. All rights reserved.