Unity 2D移动端按钮C#脚本失效,求触摸触发操作实现方案
有效触摸触发操作的Unity脚本示例及解决方法
一、针对UI元素的触摸点击方案
如果你的触发对象是UI控件(比如Button、Image),采用以下方案,需借助Unity的事件系统处理触摸交互:
using UnityEngine; using UnityEngine.EventSystems; public class UITouchMove : MonoBehaviour, IPointerClickHandler { public Transform moveThis; public GameObject targetPosition; // 响应UI触摸/点击事件 public void OnPointerClick(PointerEventData eventData) { if (moveThis != null && targetPosition != null) { moveThis.position = targetPosition.transform.position; } } }
注意事项
- 将脚本挂载到可交互的UI元素上
- 场景中必须存在
EventSystem对象(无则右键UI→Event System创建) - 确保UI元素的
Raycast Target选项处于勾选状态
二、针对3D/2D场景物体的触摸点击方案
如果触发对象是场景中的实体物体,通过射线检测响应触摸:
using UnityEngine; public class ObjectTouchMove : MonoBehaviour { public Transform moveThis; public GameObject targetPosition; void Update() { // 处理触摸输入 if (Input.touchCount > 0) { Touch touch = Input.GetTouch(0); if (touch.phase == TouchPhase.Began) { Ray ray = Camera.main.ScreenPointToRay(touch.position); if (Physics.Raycast(ray, out RaycastHit hit) && hit.transform == this.transform) { TriggerMove(); } } } // 兼容编辑器鼠标点击测试 if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out RaycastHit hit) && hit.transform == this.transform) { TriggerMove(); } } } void TriggerMove() { if (moveThis != null && targetPosition != null) { moveThis.position = targetPosition.transform.position; } } }
注意事项
- 将脚本挂载到需要被触摸的场景物体上
- 给该物体添加对应碰撞器(3D用BoxCollider/SphereCollider,2D用BoxCollider2D等)
- 若为2D物体,将
Physics.Raycast替换为Physics2D.Raycast - 确保主相机的
MainCamera标签已正确设置,避免Camera.main返回null
原脚本无效的核心原因
OnClick()是旧版UI回调方法,需手动在Button的Inspector面板绑定事件才会触发,无法自动响应触摸- 未编写触摸输入的检测逻辑,仅靠
OnClick()无法实现触摸触发
内容的提问来源于stack exchange,提问作者Asker
相关产品推荐
相关产品推荐

