如何在Unity 5中检测UI图像的鼠标悬停?


9

我有一幅图像,可以将其设置为四处移动以及放大和缩小。麻烦的是可以在场景中的任何位置进行缩放,但是我只希望在鼠标悬停在图像上时进行缩放。我尝试使用OnMouseEnter,OnMouseOver,事件触发器,所有三个没有对撞机,带对撞机,带触发器对撞机的触发器,以及所有这些在图像本身和空游戏对象上使用的触发器。但是这些都不起作用...所以我绝对很沮丧...有人可以在这里帮助我!

这是我的脚本:

    private float zoom;
    public float zoomSpeed;
    public Image map;

    public float zoomMin;
    public float zoomMax;

    void Update () {
        zoom = (Input.GetAxis("Mouse ScrollWheel") * Time.deltaTime * zoomSpeed);
        map.transform.localScale += new Vector3(map.transform.localScale.x * zoom, map.transform.localScale.y * zoom, 0);
        Vector3 scale = map.transform.localScale;
        scale = new Vector3(Mathf.Clamp(map.transform.localScale.x, zoomMin, zoomMax), Mathf.Clamp(map.transform.localScale.y, zoomMin, zoomMax), 0);
        map.transform.localScale = scale;
    }

Answers:


12

您可以实现IPointerEnterIPointerExit接口,并将布尔值保留为“ over state”:

using System;
using UnityEngine;
using UnityEngine.EventSystems;

public class TestOver : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    public bool isOver = false;

    public void OnPointerEnter(PointerEventData eventData)
    {
        Debug.Log("Mouse enter");
        isOver = true;
    }

    public void OnPointerExit(PointerEventData eventData)
    {
        Debug.Log("Mouse exit");
        isOver = false;
    }
}

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.