using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
//*****************************************************脚本挂在需要拖动的Button或者Image即可***************************************************************
public class DragSpawn : MonoBehaviour, IPointerDownHandler
{
//正在拖拽的物体
private GameObject _objDragSpawning;
//是否正在拖拽
private bool _isDragSpawning = false;
public Image image;
// Update is called once per frame
void Update () {
if (_isDragSpawning)
{
//刷新位置
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
LayerMask aa = 1 << 8;
if (Physics.Raycast (ray,out hit ,100f,aa))
{
_objDragSpawning.SetActive(true);
_objDragSpawning.transform.position = hit.point;
image.enabled = false;
}
else
{
image.enabled = true;
_objDragSpawning.SetActive(false);
image.transform.position = Input.mousePosition;
}
//_objDragSpawning.transform.position = ray.GetPoint(10);
//结束拖拽
if (Input.GetMouseButtonUp(0))
{
_isDragSpawning = false;
_objDragSpawning = null;
}
}
}
//按下鼠标时开始生成实体
public void OnPointerDown(PointerEventData eventData)
{
GameObject prefab = Resources.Load<GameObject>("person");
if(prefab != null)
{
_objDragSpawning = Instantiate(prefab);
_isDragSpawning = true;
}
}
}下面附上Demo链接:
链接:https://pan.baidu.com/s/18VhVJqXJzrltIJz\_he-JvQ
提取码:k5kg
复制这段内容后打开百度网盘手机App,操作更方便哦