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

Unity 2019.4 UI-Builder自定义Port点击拾取无法覆盖整个元素问题

Unity 2019.4 GraphView Port垂直排布拾取异常解决方案

问题根因

Unity 2019.4版本内置Port类的点击拾取逻辑默认仅适配水平排布规则,硬编码了水平方向的坐标校验规则,修改为Column/ReverseColumn垂直排布后,拾取判定逻辑未同步适配,因此出现仅半区可选中的问题。

修复方案

方案1:重写Port拾取逻辑(推荐,永久生效)

自定义Port子类重写ContainsPoint方法,取消默认的方向限制,使整个Port布局区域都可被拾取:

using UnityEngine.UIElements;
using UnityEditor.Experimental.GraphView;
using System;

public class VerticalLayoutPort : Port
{
    protected VerticalLayoutPort(Orientation portOrientation, Direction portDirection, Capacity portCapacity, Type type) 
        : base(portOrientation, portDirection, portCapacity, type) { }

    // 重写拾取判定,直接命中整个布局区域
    public override bool ContainsPoint(Vector2 localPoint)
    {
        return layout.Contains(localPoint);
    }

    // 对外创建方法,和官方Port调用逻辑对齐
    public static VerticalLayoutPort Create(Direction direction, Capacity capacity, Type portDataType)
    {
        var port = new VerticalLayoutPort(Orientation.Vertical, direction, capacity, portDataType);
        // 直接内置垂直排布的flexDirection配置
        port.style.flexDirection = direction switch
        {
            Direction.Input => FlexDirection.Column,
            Direction.Output => FlexDirection.ReverseColumn,
            _ => port.style.flexDirection.value
        };
        return port;
    }
}

后续创建Port时直接调用VerticalLayoutPort.Create替代官方Port.Create方法即可。

方案2:无侵入临时修复(无需自定义子类)

如果不想修改Port的继承逻辑,可以为Port添加一层铺满全区域的透明遮罩,手动接管点击事件透传给Port:

// 你原有创建Port的逻辑
Port port = Port.Create<Edge>(Orientation.Vertical, direction, capacity, typeof(bool));
port.style.flexDirection = direction == Direction.Input ? FlexDirection.Column : FlexDirection.ReverseColumn;

// 添加透明点击遮罩
VisualElement clickMask = new VisualElement();
clickMask.style.width = Length.Percent(100);
clickMask.style.height = Length.Percent(100);
clickMask.pickingMode = PickingMode.Position;
// 透传点击事件到父级Port
clickMask.RegisterCallback<MouseDownEvent>(evt =>
{
    evt.StopImmediatePropagation();
    port.SendEvent(evt);
});
port.Add(clickMask);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:54:01