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

Unity AR射线检测脚本报错CS1503:无法将Touch转换为Vector2

AR射线检测CS1503类型转换错误解决

错误信息

级别代码描述项目文件行号抑制状态
错误CS1503参数1:无法从‘UnityEngine.Touch’转换为‘UnityEngine.Vector2’Assembly-CSharpC:\Users\tengi\planedetection\Assets\Raycast_Script.cs

问题原因

ARRaycastManager.Raycast()方法要求第一个参数为屏幕坐标类型的Vector2,但代码中直接传入了Input.GetTouch(0)返回的Touch对象,导致类型不匹配触发报错。

修复后代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;

public class Raycast_Script : MonoBehaviour
{
    public GameObject spawn_prefab;
    GameObject spawned_object;
    bool object_spawned;
    ARRaycastManager arrayman;
    List<ARRaycastHit> hits = new List<ARRaycastHit>();

    void Start()
    {
        object_spawned = false;
        arrayman = GetComponent<ARRaycastManager>();
    }

    void Update()
    {
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            // 传入触摸点的屏幕坐标(Vector2类型)
            if (arrayman.Raycast(touch.position, hits, TrackableType.PlaneWithinPolygon))
            {
                var hitpose = hits[0].pose;
                if (!object_spawned)
                {
                    spawned_object = Instantiate(spawn_prefab, hitpose.position, hitpose.rotation);
                    object_spawned = true;
                }
                else
                {
                    spawned_object.transform.position = hitpose.position;
                }
            }
        }
    }
}

修复说明

  • 核心修改:将arrayman.Raycast(Input.GetTouch(0), ...)改为arrayman.Raycast(Input.GetTouch(0).position, ...),确保传入的是符合要求的Vector2类型屏幕坐标。
  • 也可以先获取Touch对象再提取position属性,写法更清晰,两种方式都能解决类型转换错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 13:24:55