Sunday, March 4, 2018

c# - How to detect mouse over for UI image in Unity 5?


I have an image that I have setup to move around and zoom in and out from. The trouble is the zoom can be done from anywhere in the scene, but I only want it to zoom when the mouse is hovering over the image. I have tried to use OnMouseEnter, OnMouseOver, event triggers, all three of those without a collider, with a collider, with a trigger collider, and all of that on the image itself and on an empty game object. However none of those have worked...So I am absolutely stumped...Could someone help me out here!


Here is my script:


    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;
}

Answer



You can implement IPointerEnter and IPointerExit interfaces and keep boolean for '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;
}
}

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...