Unity génère des objets à partir de la barre d'outils
- Dans le panneau Hiérarchie, créez une nouvelle image pour la forme de l'objet après avoir fait glisser
- Créez un nouveau dossier Resources sous le fichier Assets et un nouveau dossier Prefabs sous le dossier Resources
- 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é
- 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;
}
void Update()
{
if (isDragSpawning)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
objDragSpawning.transform.position = ray.GetPoint(10);
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;
}
}
}