接上一篇 ui拖动生成物体
---------------------------------------------------------------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
/// <summary>
/// 拖动场景中物体
/// </summary>
/// ----------------------------------物体需要Collider组件,否则检测不到物体
public class DragObjects : MonoBehaviour
{
private bool isDrag;
private void Update()
{
//开始拖拽
if (isDrag)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 1000f))
{
transform.position = hit.point;
}
if (Input.GetMouseButtonUp(0))
{
isDrag = false;
transform.GetComponent<BoxCollider>().enabled = true;
}
}
}
//点击到物体
private void OnMouseDown()
{
isDrag = true;
transform.GetComponent<BoxCollider>().enabled = false;
}
}
在物体上挂载此脚本 即可拖动物体
DEMO地址
|