unity ui中使用onmouseover

Posted zhoushiya

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了unity ui中使用onmouseover相关的知识,希望对你有一定的参考价值。

unity ui中鼠标移进或者移出的触发方式与2d、3d的不同,2d、3d物体使用的是onmouseover,ui使用的是OnPointerEnter。需要实现以下两个接口。

public class TrackMouse: MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
    // Called when the pointer enters our GUI component.
    // Start tracking the mouse
    public void OnPointerEnter( PointerEventData eventData )
    {
        StartCoroutine( "TrackPointer" );          
    }
 
    // Called when the pointer exits our GUI component.
    // Stop tracking the mouse
    public void OnPointerExit( PointerEventData eventData )
    {
        StopCoroutine( "TrackPointer" );
    }
 
    IEnumerator TrackPointer()
    {
        var ray = GetComponentInParent<GraphicRaycaster>();
        var input = FindObjectOfType<StandaloneInputModule>();
 
        if( ray != null && input != null )
        {
            while( Application.isPlaying )
            {                  
                Vector2 localPos; // Mouse position  
                RectTransformUtility.ScreenPointToLocalPointInRectangle( transform as RectTransform, Input.mousePosition, ray.eventCamera, out localPos );
                     
                // local pos is the mouse position.
                     
                yield return 0;
            }      
        }
        else
            UnityEngine.Debug.LogWarning( "Could not find GraphicRaycaster and/or StandaloneInputModule" );      
    }
}
 

  原文出自unity官方论坛,详情可以查看https://forum.unity.com/threads/problem-with-onmousedown-onmouseover-in-ui.326096/

 

以上是关于unity ui中使用onmouseover的主要内容,如果未能解决你的问题,请参考以下文章

unity3d新建项目之后界面一片空白,怎么解决问题?(有图)

Unity中解决“SetDestination“ can only be called on an active agent that has been placed on a NavMesh(代码片

Unity5.6发布后场景中一片粉色(缺少颜色材质),同时unity界面下方console报错

Unity 代码设置UI尺寸的一种方法

Unity 2020.1.0f1 缺少 UnityEngine.UI

unity中UI的屏幕自适应代码