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,操作更方便哦