Unity NGUI的拖动效果,并在鼠标松开时执行某个事件

本文介绍了一个Unity中实现UI元素拖拽的具体方法。通过继承MonoBehaviour类,使用Input.mousePosition来判断鼠标位置,并创建锚点对象进行拖动,最终实现了UI元素的拖放功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DragNGUI : MonoBehaviour {

    private bool m_isDrag = false;

    private bool m_temp_bool = false;

    private GameObject m_Anchor = null;
    private UIAtlas m_Atlas = null;
    private string m_NameSprite = null;

    private int m_Width = 60;
    private int m_Height = 60;

    // Use this for initialization
    void Start()
    {
        if (this.GetComponent<UISprite>())
        {
            m_Atlas = this.GetComponent<UISprite>().atlas;
            m_NameSprite = this.GetComponent<UISprite>().spriteName;
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (!m_temp_bool && StaticFunction.IsHoverNGUI(Input.mousePosition) == this.gameObject)
        {
            //Debug.Log(StaticFunction.IsHoverNGUI(Input.mousePosition).name);
            if (Input.GetMouseButtonDown(0))
            {
                m_isDrag = true;
                m_temp_bool = true;

                CreateAnchorObj();
            }
        }

        if (m_temp_bool && m_isDrag)
        {
            Drag();
        }

        if (m_temp_bool && Input.GetMouseButtonUp(0))
        {
            m_isDrag = false;
            m_temp_bool = false;
            Destroy(m_Anchor);

            Config.IsCreateMan = true;
        }
    }

    private void CreateAnchorObj()
    {
        m_Anchor = new GameObject("Anchor");
        m_Anchor.transform.parent = GameObject.Find("UI Root").transform;
        m_Anchor.transform.localPosition = Vector3.zero;

        if (m_Atlas != null)
        {
            m_Anchor.AddComponent<UISprite>();
            UISprite temp = m_Anchor.GetComponent<UISprite>();
            temp.atlas = m_Atlas;
            temp.spriteName = m_NameSprite;
            //m_Anchor.GetComponent<UIWidget>().width = this.GetComponent<UIWidget>().width;
            //m_Anchor.GetComponent<UIWidget>().height = this.GetComponent<UIWidget>().height;

            m_Anchor.GetComponent<UIWidget>().width = m_Width;
            m_Anchor.GetComponent<UIWidget>().height = m_Height;
        }

        m_Anchor.transform.localScale = new Vector3(1, 1, 1);
    }

    private void Drag()
    {
        if (!m_Anchor) return;

        Vector3 temp = Input.mousePosition;
        temp.x -= Screen.width / 2.0f;
        temp.y -= Screen.height / 2.0f;
        m_Anchor.transform.localPosition = temp;
        //this.transform.position = m_Anchor.transform.position;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值