Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Block raycast through the UI

Discussion in 'Scripting' started by CF_Sixdotsstudios, Nov 6, 2020.

  1. CF_Sixdotsstudios

    CF_Sixdotsstudios

    Joined:
    Apr 10, 2020
    Posts:
    92
    Code (CSharp):
    1. public Camera cam;
    2.  
    3.     public NavMeshAgent agent;
    4.  
    5.     // Update is called once per frame
    6.     public void MoveToLocation()
    7.     {
    8.         Ray ray = cam.ScreenPointToRay(Input.mousePosition);
    9.         RaycastHit hit;
    10.  
    11.         if (Physics.Raycast(ray, out hit))
    12.         {
    13.             agent.SetDestination(hit.point);
    14.         }
    15.     }
    how do i stop the above code from executing on my UI or buttons? my player keeps moving with every click when i access my menu
     
  2. diego-giacomelli

    diego-giacomelli

    Joined:
    Oct 27, 2012
    Posts:
    26
    Try to add a GraphicRaycaster to the Canvas.

    The Graphic Raycaster is used to raycast against a Canvas. The Raycaster looks at all Graphics on the canvas and determines if any of them have been hit.
     
    shauli21 likes this.
  3. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,722
  4. CF_Sixdotsstudios

    CF_Sixdotsstudios

    Joined:
    Apr 10, 2020
    Posts:
    92
    thank u... will have a loook
     
  5. MrPaparoz

    MrPaparoz

    Joined:
    Apr 14, 2018
    Posts:
    156
    Code (CSharp):
    1. public Camera cam;
    2.     public NavMeshAgent agent;
    3.     // Update is called once per frame
    4.     public void MoveToLocation()
    5.     {
    6.         Ray ray = cam.ScreenPointToRay(Input.mousePosition);
    7.         bool isOverUI = UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject();
    8.         if (Physics.Raycast(ray, out RaycastHit hit) && ! isOverUI)
    9.         {
    10.             agent.SetDestination(hit.point);
    11.         }
    12.     }
    Edit: You'll need a EventSystem component in scene.
     
  6. CF_Sixdotsstudios

    CF_Sixdotsstudios

    Joined:
    Apr 10, 2020
    Posts:
    92
    Thank u so much for your input...
     
  7. DucaDiMonteSberna

    DucaDiMonteSberna

    Joined:
    Jan 18, 2018
    Posts:
    51
    Code (CSharp):
    1. private bool DefineOnUI()
    2.     {
    3.         //Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    4.         if (EventSystem.current.IsPointerOverGameObject())
    5.         {
    6.             Debug.Log("Clicked on the UI");
    7.             return true;
    8.         }
    9.         else
    10.         {
    11.             return false;
    12.         }
    13.     }
    for future reference
     
    Eristen and rgarcez like this.