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

适配Microsoft Mesh时Unity Visual Scripting Physics Raycast未暴露Hit对象

解决Unity Visual Scripting中Physics Raycast无Hit输出的问题

方法1:自定义Raycast节点(推荐)

  • 写一个C#脚本封装原生射线检测逻辑,手动暴露RaycastHit输出:
using UnityEngine;
using UnityEngine.VisualScripting;

[UnitTitle("Custom Raycast")]
[UnitCategory("Physics")]
public class CustomRaycastUnit : Unit
{
    [DoNotSerialize]
    public ValueInput origin;
    
    [DoNotSerialize]
    public ValueInput direction;
    
    [DoNotSerialize]
    public ValueInput maxDistance;
    
    [DoNotSerialize]
    public ValueInput layerMask;
    
    [DoNotSerialize]
    public ValueOutput hit;
    
    [DoNotSerialize]
    public ValueOutput hitResult;

    protected override void Definition()
    {
        origin = ValueInput<Vector3>(nameof(origin), Vector3.zero);
        direction = ValueInput<Vector3>(nameof(direction), Vector3.forward);
        maxDistance = ValueInput<float>(nameof(maxDistance), Mathf.Infinity);
        layerMask = ValueInput<int>(nameof(layerMask), -1);
        
        hitResult = ValueOutput<bool>(nameof(hitResult), ExecuteRaycast);
        hit = ValueOutput<RaycastHit>(nameof(hit), GetHit);
        
        Requirement(origin, hitResult);
        Requirement(direction, hitResult);
        Requirement(maxDistance, hitResult);
        Requirement(layerMask, hitResult);
        Requirement(hitResult, hit);
    }

    private RaycastHit _lastHit;
    
    private bool ExecuteRaycast(Flow flow)
    {
        var originVal = flow.GetValue<Vector3>(origin);
        var directionVal = flow.GetValue<Vector3>(direction);
        var maxDistVal = flow.GetValue<float>(maxDistance);
        var layerMaskVal = flow.GetValue<int>(layerMask);
        
        return Physics.Raycast(originVal, directionVal, out _lastHit, maxDistVal, layerMaskVal);
    }
    
    private RaycastHit GetHit(Flow flow)
    {
        return _lastHit;
    }
}
  • 把脚本放到项目Assets/Scripts/VisualScripting目录,重新编译后,就能在Visual Scripting面板找到Custom Raycast节点,它会同时输出碰撞布尔值和完整RaycastHit对象,直接连getDistance节点就行。

方法2:原生节点组合替代(仅适用于获取距离场景)

如果不想写脚本,可通过节点组合计算距离:

  • 射线检测成功后,用Get Component节点获取碰撞物体的Transform;
  • 用Transform.position节点拿到碰撞点坐标;
  • 将射线原点和碰撞点坐标传入Vector3.Distance节点,得到检测距离。

注意:这个方法只能获取距离,若需要Hit对象的法线、碰撞体等其他属性,还是用方法1更稳妥。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 16:56:14