Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

[Editor Script] Raycast in editor problem and selection woe's

Discussion in 'Immediate Mode GUI (IMGUI)' started by Superflat, Sep 13, 2011.

  1. Superflat

    Superflat

    Joined:
    Mar 19, 2009
    Posts:
    354
    Hello,

    I'm writing myself a tool that let's me place an object on anything that has a collider, properly rotated according to the normal the ray has hit.

    Now i got a basic version working where you press a gui button on a custom inspector and then you need to S***+click to place the object. Two things happens: 1) The ray doesnt seem to be coming from the camera for some reason. Objects arent placed where i click. 2) After the script places the object, it will shift-select the target that i clicked as well.

    What do? ;(

    Code (csharp):
    1. public void OnSceneGUI()
    2.     {      
    3.         if(placingObject)
    4.         {
    5.             if(Event.current.shift  Event.current.type == EventType.mouseDown)
    6.             {
    7.                 Ray ray = Camera.current.ScreenPointToRay(Event.current.mousePosition);
    8.                 RaycastHit hit = new RaycastHit();
    9.                 if(Physics.Raycast(ray, out hit, 1000.0f))
    10.                 {
    11.                     t.position = hit.point;
    12.                     t.rotation = Quaternion.FromToRotation(t.up, hit.normal) * t.rotation;
    13.                 }
    14.                 placingObject = false;
    15.             }
    16.  
    17.             Selection.activeGameObject = t.gameObject;
    18.  
    19.         }
     
  2. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052
    I'm bumping this, having the exact same problem... the ray doesn't seem to hit where I click, it's somehow "Offset" by the camera position or rotation, not sure how.
     
  3. fholm

    fholm

    Joined:
    Aug 20, 2011
    Posts:
    2,052
    Solved it, the trick is to use: HandleUtility.GUIPointToWorldRay(@event.mousePosition) instead of Camera.current...
     
    Tepei, PhoenixRising1, infuzo and 2 others like this.
  4. vlevykin

    vlevykin

    Joined:
    Dec 29, 2012
    Posts:
    1
    Thanks, fholm!
     
  5. Mungyun

    Mungyun

    Joined:
    Jan 9, 2013
    Posts:
    2
    This problem was driving me nuts! Everywhere i looked told me to use Camera.current..

    Thanks for posting this =-D
     
  6. afuzzyllama

    afuzzyllama

    Joined:
    May 19, 2010
    Posts:
    20
    This needs to be referenced in all Camera.current answers. Solved my issue instantly