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. Join us on Thursday, June 8, for a Q&A with Unity's Content Pipeline group here on the forum, and on the Unity Discord, and discuss topics around Content Build, Import Workflows, Asset Database, and Addressables!
    Dismiss Notice

Resolved How to detect which collider is clicked in 3D

Discussion in 'Scripting' started by DZZc0rd, Mar 27, 2023.

  1. DZZc0rd

    DZZc0rd

    Joined:
    Sep 4, 2021
    Posts:
    45
    I wanna make point & click game and I want to add movement by clicking on object, but to do this I need make 2 colliders for object and I wanna detect which collider is clicked.

    Version: 2021.3.14f1
     
  2. DZZc0rd

    DZZc0rd

    Joined:
    Sep 4, 2021
    Posts:
    45
    I found solution, here code:

    Code (CSharp):
    1. private void OnMouseDown()
    2. {
    3.     if (Input.GetMouseButtonDown(0))
    4.     {
    5.         RaycastHit hit;
    6.         if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
    7.         {
    8.             if (hit.collider == GetComponents<Collider>()[0])
    9.                 // On first collider
    10.             else if (hit.collider == GetComponents<Collider>()[1])
    11.                 // On second collider
    12.              // More `else if` if you have more colliders
    13.         }
    14.     }
    15. }
    But you need to remember what index for each colliders
     
    Last edited: Mar 27, 2023
  3. QuinnWinters

    QuinnWinters

    Joined:
    Dec 31, 2013
    Posts:
    490
    Just a suggestion: It would be cheaper on overhead if you stored a reference to your colliders on Start rather than running two or more GetComponents every time you click.

    Code (CSharp):
    1.     Collider collider0;
    2.     Collider collider1;
    3.  
    4.     private void Start ()
    5.     {
    6.         collider0 = GetComponents<Collider>()[0];
    7.         collider1 = GetComponents<Collider>()[1];
    8.     }
    9.  
    10.     private void OnMouseDown()
    11.     {
    12.         if (Input.GetMouseButtonDown(0))
    13.         {
    14.             RaycastHit hit;
    15.             if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition), out hit))
    16.             {
    17.                 if (hit.collider == collider0)
    18.                     // On first collider
    19.                 else if (hit.collider == collider1)
    20.                     // On second collider
    21.                  // More `else if` if you have more colliders
    22.             }
    23.         }
    24.     }
     
  4. DZZc0rd

    DZZc0rd

    Joined:
    Sep 4, 2021
    Posts:
    45
    This solution is better if each collider will be used multiple times