1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4using UnityEngine.EventSystems; 5using UnityEngine.UI; 6//*****************************************************脚本挂在需要拖动的Button或者Image即可*************************************************************** 7public class DragSpawn : MonoBehaviour, IPointerDownHandler 8{ 9 //正在拖拽的物体 10 private GameObject _objDragSpawning; 11 12 //是否正在拖拽 13 private bool _isDragSpawning = false; 14 public Image image; 15 // Update is called once per frame 16 void Update () { 17 if (_isDragSpawning) 18 { 19 //刷新位置 20 Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 21 RaycastHit hit; 22 LayerMask aa = 1 << 8; 23 if (Physics.Raycast (ray,out hit ,100f,aa)) 24 { 25 _objDragSpawning.SetActive(true); 26 _objDragSpawning.transform.position = hit.point; 27 image.enabled = false; 28 } 29 else 30 { 31 image.enabled = true; 32 _objDragSpawning.SetActive(false); 33 image.transform.position = Input.mousePosition; 34 } 35 //_objDragSpawning.transform.position = ray.GetPoint(10); 36 37 //结束拖拽 38 if (Input.GetMouseButtonUp(0)) 39 { 40 _isDragSpawning = false; 41 _objDragSpawning = null; 42 } 43 } 44 } 45 46 //按下鼠标时开始生成实体 47 public void OnPointerDown(PointerEventData eventData) 48 { 49 GameObject prefab = Resources.Load<GameObject>("person"); 50 if(prefab != null) 51 { 52 _objDragSpawning = Instantiate(prefab); 53 _isDragSpawning = true; 54 } 55 56 } 57 58}下面附上Demo链接:
链接:https://pan.baidu.com/s/18VhVJqXJzrltIJz\_he-JvQ
提取码:k5kg
复制这段内容后打开百度网盘手机App,操作更方便哦