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

Which is the best way to detect colliders between 2 objects in unity?

Discussion in 'Scripting' started by unity_1236alman, Feb 26, 2021.

  1. unity_1236alman

    unity_1236alman

    Joined:
    Mar 4, 2019
    Posts:
    66
    I need to know if between me and a tile on the map there is a particular object, so i should make a line starting from me to the target object. The problem is that i need only the objects that intersect this line.
     
  2. IcePhoenix_0101

    IcePhoenix_0101

    Joined:
    Sep 9, 2017
    Posts:
    32
  3. Putcho

    Putcho

    Joined:
    Jun 1, 2013
    Posts:
    246
    is this what you try to do?
     
  4. unity_1236alman

    unity_1236alman

    Joined:
    Mar 4, 2019
    Posts:
    66
    yes
     
  5. Putcho

    Putcho

    Joined:
    Jun 1, 2013
    Posts:
    246
  6. Putcho

    Putcho

    Joined:
    Jun 1, 2013
    Posts:
    246
    Code (CSharp):
    1. public class SampleClass : MonoBehaviour
    2.     {
    3.         public Transform m_target;
    4. //mask of an object that can get hit by ray
    5.         public LayerMask m_mask;
    6.  
    7.         void Update()
    8.         {
    9.  
    10.             //Calculate the direction where the target is in worldspace
    11.             Vector3 direction = m_target.position - transform.position;
    12.             //find out the distance between you and the target
    13.             float distance = Vector3.Distance(transform.position, m_target.position);
    14.  
    15.             RaycastHit[] hits; // all Objects that are on top the line will listed here temporarily, you can create some manager to keep track these data
    16.             hits = Physics.RaycastAll(transform.position, direction, distance, m_mask);
    17.  
    18.             for (int i = 0; i < hits.Length; i++)
    19.             {
    20.                 RaycastHit hit = hits[i];
    21.  
    22.                 Debug.Log(hit.transform.gameObject.name);
    23.             }
    24.         }
    25.     }
    26.  
    27. //this is basic modify as you like
     
    unity_1236alman likes this.
  7. unity_1236alman

    unity_1236alman

    Joined:
    Mar 4, 2019
    Posts:
    66
    thanks
     
    Putcho likes this.