Author Topic: Blocking Raycast through NGUI Buttons  (Read 6592 times)

BenKurdziel

  • Guest
Blocking Raycast through NGUI Buttons
« on: March 02, 2013, 09:04:58 PM »
So I've seen some questions about this, but I haven't been able to find a definitive answer that worked for me.

So my situation is basically that I'm raycasting from my Main Camera which shows my level to my current mouse position in relation to the world. Then when I click I create a second raycast that tests what I clicked on and returns the gameObject.tag to me so that I can do stuff depending on the type of object.

What I THINK is wrong:
My NGUI stuff is located at 0,0,0 over in the corner of the world and it looks normal in game and works like it should as far as clicking and making menus pop up. However, on my actually screen, since I have 2 cameras, and the raycast is coming from the Main Camera, it's not realizing that there is a button there in the game because the actual location of the NGUI elements is 0,0,0.

I'm not sure if I should be parenting the UI Root to the Main Camera to make it show up that way, or if there's a way to make the raycast detect those buttons anyway (realize they are there on screen in runtime even though they aren't physically there in the scene). I really need the raycast to not go through those on screen elements because it allows the player to place objects in places they shouldn't be able to and it causes all sorts of bugs.

Any help would be GREATLY appreciated.
« Last Edit: March 02, 2013, 09:07:01 PM by BenKurdziel »

nzen

  • Newbie
  • *
  • Thank You
  • -Given: 0
  • -Receive: 1
  • Posts: 30
    • View Profile
Re: Blocking Raycast through NGUI Buttons
« Reply #1 on: March 03, 2013, 03:57:40 AM »
I think you have to scrap your own raycasts, as NGUI does them. Then you need a UICamera script on your MainCamera (just use NGUI > Camera Tool > Tick EV). Modify the Event Receiver Mask in UICamera to your needs.

So this (will go straight through a GUI):
  1. Ray ray = yourMainCamera.ScreenPointToRay(Input.mousePosition);
  2. RaycastHit hitInfo;
  3.  
  4. if (Physics.Raycast(ray, out hitInfo, 100f, layerMask))
  5. {
  6.         if (hitInfo.collider.gameObject.tag == "YourTag")
  7.         {
  8.                 Instantiate(obj, hitInfo.point, Quaternion.identity);
  9.         }
  10. }

Becomes this:
  1. if (UICamera.hoveredObject.tag == "YourTag")
  2. {
  3.         Instantiate(obj, UICamera.lastHit.point, Quaternion.identity);
  4. }

Now clicking a GUI button will not run the code. At least that's how I do it. Maybe there is another way.

If you want Sprites to block, then you have to add a collider to them. Also, I don't think the UI Root should be parented to the Main Camera.

And maybe wrap this in a "if (UICamera.hoveredObject != null)".
« Last Edit: March 03, 2013, 04:15:41 AM by nzen »