Unity génère des objets à partir de la barre d'outils

Unity génère des objets à partir de la barre d'outils

  1. Dans le panneau Hiérarchie, créez une nouvelle image pour la forme de l'objet après avoir fait glisser
  2. Créez un nouveau dossier Resources sous le fichier Assets et un nouveau dossier Prefabs sous le dossier Resources
  3. Créez un modèle, en supposant qu'il s'appelle Cube, faites-le glisser et déposez-le dans le dossier Prefabs pour devenir un préfabriqué
  4. Créez une interface utilisateur (bouton, texte, image, etc.) et montez le script sur 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