What shall I use instead of OnMouseXXX event handl

2019-07-13 01:11发布

问题:

I've build a little app where I use OnMouseDrag and OnMouseDown in some objects. I thought that it would be the best option because this methods were out of the Update method. However at compiling the app Unity says "Game scripts or other custom code contains OnMouseXXX event handlers. Presence of such handlers might impact performance on handheld devices."

So... what should I use instead of OnMouseDrag and OnMouseDown?

I've seen that i could use Input.GetMouseButtonDown. But to do this I will have to add an Update method to every object that has the OnMouseDown. Isn't it worst than having the OnMouseDrag?

And, why are OnMouseXXX events bad for the performance in on handheld devices?

回答1:

And, why are OnMouse events bad for the performance in on handheld devices?

They are not bad for performance. I haven't experienced any bad performance with them but the reason you are getting that error is because it is likely that Unity is doing more work on mobile in order to get it working. It's not made for that but you should't notice any performance hit just by using them.

So... what should I use instead of OnMouseDrag and OnMouseDown?

The OnMouseDrag and OnMouseDown functions were specifically made for desktops. Yes, they work on mobile devices too but should be avoided.

They should be avoided because they don't work for all Objects. For example, they don't work on the new UGUI system.

You should be using OnBeginDrag and OnEndDrag which both requires you implement IBeginDragHandler and IEndDragHandler.

The OnBeginDrag and OnEndDrag functions will work on all GameObjects including 3D, 2D and the UI. For 2D you need to attach Physics2DRaycaster to the camera. For 3D, you have to attach PhysicsRaycaster to the camera.

See this post for how to get it work on any GameObject.

using UnityEngine.EventSystems;

public class Dragger: MonoBehaviour,
    IBeginDragHandler, IEndDragHandler
{
    public void OnBeginDrag(PointerEventData eventData)
    {
        Debug.Log("Drag Begin");
    }

    public void OnDrag(PointerEventData eventData)
    {
        Debug.Log("Dragging");
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        Debug.Log("Drag Ended");
    }
}