Unity AR射线检测脚本报错CS1503:无法将Touch转换为Vector2
AR射线检测CS1503类型转换错误解决
错误信息
| 级别 | 代码 | 描述 | 项目 | 文件 | 行号 | 抑制状态 |
|---|---|---|---|---|---|---|
| 错误 | CS1503 | 参数1:无法从‘UnityEngine.Touch’转换为‘UnityEngine.Vector2’ | Assembly-CSharp | C:\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
相关产品推荐
相关产品推荐

