unity 從工具欄拖動生成物體


using System.Collections;
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,操作更方便哦

 
        

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM