美文网首页虚拟仿真
unity 从工具栏拖动生成物体

unity 从工具栏拖动生成物体

作者: 一飞同学丶走慢点 | 来源:发表于2023-04-03 15:16 被阅读0次
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,操作更方便哦

相关文章

网友评论

    本文标题:unity 从工具栏拖动生成物体

    本文链接:https://www.haomeiwen.com/subject/vxzdddtx.html