Search Unity

Detecting what mouse clicked on the scene editor window

Discussion in 'Scripting' started by davvilla, Apr 27, 2012.

  1. davvilla

    davvilla

    Joined:
    Mar 28, 2012
    Posts:
    18
    I'm developing a tile editor within unity and I want to be able to detect what the mouse is clicking on (in the scene editor window). I know this is not a new topic but I did a lot of research but my ray calculations seem to be off for some reason.

    Code (csharp):
    1.  
    2.     void SceneGUI(SceneView sceneview) {
    3.         if (Event.current.type == EventType.mouseDown) {
    4.        
    5.             if (Camera.current != null) {
    6.                 Ray ray = Camera.current.ScreenPointToRay(Input.mousePosition);
    7.                
    8.                 RaycastHit hit = new RaycastHit();
    9.                 Debug.DrawLine(ray.origin, ray.origin + ray.direction * 1000);
    10.                
    11.                 if (Physics.Raycast(ray, out hit)) {
    12.                     Debug.Log("hit");
    13.                 } else {
    14.                     Debug.Log("miss");
    15.                 }
    16.             } else {
    17.                 Debug.Log("camera is null");
    18.             }
    19.         }
    20.     }
    21.  
    I always end up getting a miss. I checked and Camera.current is in fact the camera of the editor. I've tried every permutation of the Raycast() function and none seem to work for me. Does anyone have any idea what I might be doing wrong?

    Thanks!
    David Villarreal
     
    michaeleconomy likes this.
  2. davvilla

    davvilla

    Joined:
    Mar 28, 2012
    Posts:
    18
    I just realized I was getting Input.mousePosition, I changed that to Event.current.mousePosition and it seems to be getting the correct calculations now. It still says I missed it, but the debug line seems to be going through it now.
     
  3. davvilla

    davvilla

    Joined:
    Mar 28, 2012
    Posts:
    18
    I fixed it, my object did not have a collider and hence it wasn't detecting anything. Ignore this thread!
     
  4. Chunks

    Chunks

    Joined:
    Jul 30, 2012
    Posts:
    4
    What type of class are you using this code in?

    This isn't in an EditorWindow, is it?