unity 从工具栏拖动生成物体

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,操作更方便哦
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容