Unity点击物体后,移动到物体所在位置
方法一:OnMouse检测(需要Collider组件)
脚本挂在被点击的物体上
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;/// <summary>
/// 缺点:要挂在所有需要被检测的物体上
/// </summary>
public class Move01 : MonoBehaviour
{public GameObject Player; //可以直接通过手动拖拽找到物体,也可以通过名字或tag查找private void Start(){//Player = GameObject.Find("Player"); //通过名字查找物体//Player = GameObject.FindWithTag("cube"); //通过tag查找物体}void OnMouseDown(){Player.transform.localPosition = this.transform.localPosition; //position是世界位置,localPosition是相对父节点的位置;如果物体没有父节点,localpositon和position没有区别;如果物体有父节点,用positionDebug.Log("已移动");}
}
方法二: 射线检测(需要Collider组件)
脚本挂在角色控制器上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;/// <summary>
/// 缺点:当场景中有大量物体时,会检测最近的物体,导致无法获取真正想要得到的物体
/// </summary>
public class Move02 : MonoBehaviour
{Ray ray;RaycastHit hit;GameObject obj;private void Update(){if (Input.GetMouseButtonDown(0)){ray = Camera.main.ScreenPointToRay(Input.mousePosition);if (Physics.Raycast(ray, out hit)){obj = hit.collider.gameObject;string name = obj.name;string tag = obj.tag;name = name.Trim(); //去掉名字前后的空格符tag = tag.Trim(); //去掉tag前后的空格符//通过名字判断是否是想要的路标物体if (obj.name == "Cube"){this.transform.localPosition = obj.transform.localPosition;}//通过tag判断是否是想要的路标物体if (obj.tag.Equals("cube")){this.transform.localPosition = obj.transform.localPosition;}}}}
}
改进:使用Raycast中的LayerMask
- 创建“cube”层
- 将想要被检测的物体放入该层

using System.Collections;
using System.Collections.Generic;
using UnityEngine;/// <summary>
/// 使用Raycast中的LayerMask,处理多物体场景中的特定物体检测
/// </summary>
public class move : MonoBehaviour
{Ray ray;RaycastHit hit;GameObject obj;void Update(){if (Input.GetMouseButtonDown(0)){Debug.Log("检测到点击");ray = Camera.main.ScreenPointToRay(Input.mousePosition);if (Physics.Raycast(ray, out hit, 100, LayerMask.GetMask("cube"))){obj = hit.collider.gameObject;this.transform.position =obj.transform.position;}}}
}
方法三:EventTrigger 物体动态事件监听
3.1、 3D物体事件监听
- 在相机上挂Physics Raycaster组件

- 检查是否有EventSystem

- 将脚本挂在被点击的物体上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;/// <summary>
/// 缺点:要挂在所有需要被检测的物体上
/// </summary>
public class mouseDown : MonoBehaviour
{private GameObject Player;private void Start(){Player = GameObject.Find("Player");}public void MyClick(){Player.transform.position = this.transform.position;}
}
- 添加组件Event Trigger组件


















