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/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM