Skip to content

Instantly share code, notes, and snippets.

@Cotoff
Created April 7, 2014 12:15
Show Gist options
  • Save Cotoff/10019176 to your computer and use it in GitHub Desktop.
Save Cotoff/10019176 to your computer and use it in GitHub Desktop.
This is a Unity3D script that works around colliders intercepting mouse messages when they should not. By using layer mask, this script sends messages to only those objects that need it.
using UnityEngine;
public class MouseEventSender : MonoBehaviour
{
public float RayCastDistance = float.MaxValue;
public LayerMask LayerMask;
public Camera Camera;
public int Button;
private Collider m_LastHit;
private Collider m_PressedOn;
public void Update()
{
var cam = Camera ? Camera : Camera.main;
var ray = cam.ScreenPointToRay(Input.mousePosition);
Collider hit = null;
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo, RayCastDistance, LayerMask))
hit = hitInfo.collider;
if (hit != m_LastHit)
{
if (m_LastHit)
m_LastHit.SendMessage("MouseExited",SendMessageOptions.DontRequireReceiver);
if (hit)
hit.SendMessage("MouseEntered", SendMessageOptions.DontRequireReceiver);
}
if (hit)
{
if (Input.GetMouseButtonDown(Button))
{
hit.SendMessage("MousePressed", SendMessageOptions.DontRequireReceiver);
m_PressedOn = hit;
}
else if (Input.GetMouseButtonUp(Button))
{
hit.SendMessage("MouseReleased", SendMessageOptions.DontRequireReceiver);
if (hit == m_PressedOn)
hit.SendMessage("MouseReleasedAsButton", SendMessageOptions.DontRequireReceiver);
}
else if (hit == m_LastHit)
{
hit.SendMessage(Input.GetMouseButton(Button) ? "MousePressedOver" : "MouseOver", SendMessageOptions.DontRequireReceiver);
}
}
m_LastHit = hit;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment