How can I access OnPointerEnter events with a custom cursor?

Hi,

I implemented a custom mouse, replacing the default cursor (locking & making it invisible) and using a GameObject with a Sprite instead. I move this GameObject with the Input.GetAxis values and everything works fine.

There is a problem, though: I want to use the Unity Event system, especially for UI interactions but since I don’t use the mouse cursor anymore, I can’t access Events such as OnPointerEnter and OnPointerClick.

Is there a way to access those events (or write custom ones) so I can use the Event system?

I’m reasonably sure those events are tied to the hardware cursor. If the cursor is locked to the screen’s center, the events will fire on objects occupying the center of the screen.

You can build your own solution, no problem. Though it’s worth considering allowing an unlocked cursor to avoid this. If you need a cursor in the game, the expectation is that you’ll use the hardware cursor.

Perhaps the most direct route to scripting these cursor events involves casting a ray from the camera through your custom cursor. This may be as simple as taking the vector difference between the custom cursor object and the camera.

Vector3 rayDirection = cursor.position - camera.position;

With a little raycasting, this approach should give you what you’re asking for. All you’d need to do is give the ray sufficient length, have it check the desired layers, and choose some approach to notify scripts on the objects you’re hitting. I’d recommend a custom class from which such objects will inherit, and a method on that class you invoke with the raycast which you can override on each script. (Or alternately, an IRaycastReceiver interface) Example for “On Enter” event:

public class MyBaseObject : MonoBehaviour {
  // the raycast looks for a MyBaseObject script on the hit object
  // and invokes this method if it finds an instance of MyBaseObject
  public virtual void OnRaycastEnter() {
  }
}

public class MyDerivedObject : MyBaseObject {
  // this will invoke on the derived objects, allowing custom 
  // logic per class, much like the native event system
  public override void OnRaycastEnter() {
  }
}