Unity从工具栏生成物体
- 在Hierarchy面板上,新建一个Image,用于拖动之后的物体形状
- 在Assets文件下新建Resources文件夹,Resources文件夹下新建Prefabs文件夹
- 创建一个模型,假定命名为Cube,拖放到Prefabs文件夹里成为预制体
- 创建一个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;
}
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;
}
}
}