Unity从工具栏生成物体

Unity从工具栏生成物体

  1. 在Hierarchy面板上,新建一个Image,用于拖动之后的物体形状
  2. 在Assets文件下新建Resources文件夹,Resources文件夹下新建Prefabs文件夹
  3. 创建一个模型,假定命名为Cube,拖放到Prefabs文件夹里成为预制体
  4. 创建一个UI(Button,Text,Image等都可)然后将脚本挂载到UGUI上
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class DragSpawn : MonoBehaviour, IPointerDownHandler
{
    
    
    private GameObject objDragSpawning;//正在拖拽的物体

    private bool isDragSpawning = false;//是否正在拖拽

    public Image image;//拖动之后的形状
    private void Start()
    {
    
    
        image.enabled = false;//开始image不显示
    }

    void Update()
    {
    
    
        if (isDragSpawning)
        {
    
    
            //刷新位置
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);//发出从摄像机到点击坐标的射线
            objDragSpawning.transform.position = ray.GetPoint(10);//ray.GetPoint(distance)沿着射线在distance距离单位的点

            //拖动时的image
            image.enabled = true;
            image.transform.position = Input.mousePosition;

            //拖动物体在鼠标为松开时不显示
            objDragSpawning.SetActive(false);
           
            //结束拖拽
            if (Input.GetMouseButtonUp(0))
            {
    
    
                objDragSpawning.SetActive(true);
                isDragSpawning = false;
                objDragSpawning = null;
                image.enabled = false; 
            }
        }
    }

    //按下鼠标时开始生成实体
    public void OnPointerDown(PointerEventData eventData)
    {
    
    
        GameObject prefab = Resources.Load<GameObject>("Prefabs/Cube");
        
        if (prefab != null)
        {
    
    
            objDragSpawning = Instantiate(prefab);
            isDragSpawning = true;
        }        
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45686837/article/details/122185215