Detect Mouse Click Over BoxCollider2D in Scene View (Custom Editor)
Hey guys I've seen a bunch of similar topics to mine but none seem to solve my issue. I've got a bunch of BoxCollider2D objects (I'm creating a tile-based game) in my scene and am trying to use a custom editor script to detect mouse clicks on them. Here's what I have:
private void OnSceneGUI()
{
Event e = Event.current;
if (e != null && e.type == EventType.MouseDown && e.button == 0)
{
Debug.Log("Mouse down!");
Ray r = Camera.current.ScreenPointToRay(e.mousePosition);
RaycastHit2D hitInfo = Physics2D.GetRayIntersection(r, 10f, 1 << LayerMask.NameToLayer("Tile"));
if (hitInfo.collider != null)
{
Tile t = hitInfo.collider.GetComponent<Tile>();
if (t != null)
{
// Do stuff...
e.Use();
}
}
}
}
Problem is that it's detecting mouse clicks on tiles NOWHERE NEAR the mouse. Any idea what I'm doing wrong? I'm sure it's something super obvious but I've been here for 2 nights now and still can't see it.
For the record I've also tried:
Collider2D col = Physics2D.OverlapPoint(Camera.current.ScreenToWorldPoint(e.mousePosition), 1 << Layer$$anonymous$$ask.NameToLayer("Tile"));
if (col)
{
Debug.Log("Hit: " + col.name, col);
Tile t = col.GetComponent<Tile>();
if (t != null)
{
//Debug.DrawRay(r.origin, r.direction, Color.red, 100f);
t.selected = true;
e.Use();
}
}
With no more success :/
Answer by _Morgenstern_ · Jun 16, 2016 at 09:12 PM
As expected, as soon as I post something I figure it out. Posting here in case anyone else is having the same issue.
Ray should have been calculated like so:
Ray r = HandleUtility.GUIPointToWorldRay(e.mousePosition);
Your answer
![](https://koobas.hobune.stream/wayback/20220612083106im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Unity 2019 LTS can't find scripts in "Editor" Folder. 0 Answers
Objects in Custom Editor Resetting on Play 1 Answer
How to make dynamic list custom inspector 0 Answers
EditorGUILayout.ObjectField on a ScriptableObject's inspector doesn't update properly 0 Answers
How do I draw information, extending the "Project/Assets/" Window? 0 Answers