Unity 鼠标悬停

程序实现效果:

  
 using UnityEngine.EventSystems;

  void Update()
    {
        //鼠标按下的时候认为是退出状态
        if (Input.GetKey(KeyCode.Mouse0) || Input.GetKey(KeyCode.Mouse1))
        {
            //除了leftAlt键盘之外
            if (Input.GetKey(KeyCode.LeftControl))
            {
                return;
            }
            mouse_Hover_Exit(null);
        }
    }

    void Start()
    {
        WindowCtrl_Click();
    }


    private void WindowCtrl_Click()
    {
        //添加鼠标悬浮事件
        EventTrigger trigger = GetComponent();
        if (null == trigger)
        {
            trigger = gameObject.AddComponent();
        }
        //鼠标悬停进入
        EventTrigger.Entry hoverOnEntry = new EventTrigger.Entry();
        //如果时鼠标悬浮进入
        hoverOnEntry.eventID = EventTriggerType.PointerEnter;
        hoverOnEntry.callback.AddListener((data) => { mouse_Hover_On((PointerEventData)data); });
        trigger.triggers.Add(hoverOnEntry);

        //鼠标悬浮退出
        EventTrigger.Entry hoverExitentry = new EventTrigger.Entry();
        //如果时鼠标悬浮退出
        hoverExitentry.eventID = EventTriggerType.PointerExit;
        hoverExitentry.callback.AddListener((data) => { mouse_Hover_Exit((PointerEventData)data); });
        trigger.triggers.Add(hoverExitentry);

        //鼠标悬浮退出
        EventTrigger.Entry pressEntry = new EventTrigger.Entry();
        //如果时鼠标悬浮进入
        pressEntry.eventID = EventTriggerType.PointerDown;
        pressEntry.callback.AddListener(delegate { mouse_Press_Down(); });
        trigger.triggers.Add(pressEntry);
    }

    private void mouse_Press_Down()
    {

    }

    /// 
    /// 鼠标悬停退出
    /// 
    /// 
    private void mouse_Hover_Exit(PointerEventData data)
    {
        this.gameObject.GetComponent().DOPlayBackwards();
        this.gameObject.GetComponent().UpdateParam(false);
    }

    /// 
    /// 鼠标悬停进入
    /// 
    /// 
    private void mouse_Hover_On(PointerEventData data)
    {
        this.gameObject.GetComponent().DOPlayForward();
        this.gameObject.GetComponent().UpdateParam(true);
    }

解释一下: 本人写的是当鼠标悬停在该物体上时正序播放动画,离开时则倒序播放。可以根据需求修改mouse_Hover_Exit,mouse_Hover_On,mouse_Press_Down方法即可。

知识共享许可协议
本作品由A_AiTing采用知识共享署名-非商业性使用 4.0 国际许可协议进行许可。

你可能感兴趣的:(项目总结)