title: How to stop raycast when hitting an object in Unity?
body: <p>In my Unity game (top-down 2D shooter) there are some enemies flying along a path (via DOTween). My player casts a ray into the scene in order to get an enemy-object right in front of the player. So far so good.</p>
  <p>Now the problem is that I want only one enemy-object as a result, i.e. the raycast should stop when it hits an enemy-object for the very first time. How do I achieve this?</p>
  <p>I need only one enemy-object hit by the raycast because there is a crosshair in my game and when the raycast starts and the enemies fly along the path the crosshair jumps forth and back (and I don't want this - the crosshair should stay at the first enemy hit by the raycast).</p>
  <p><a href="https://imgur.com/a/KBngql8" rel="nofollow noreferrer">Raycast video</a></p>
  <p>This is my code (attached to the player):</p>
  <pre><code>void FixedUpdate() {
      
      //crosshair: Cast a ray straight up.
      float _size = 12f;
          Vector2 _direction = this.transform.up;
          RaycastHit2D _hit = Physics2D.Raycast(this.transform.position, _direction, _size);
  
      if (_hit.collider != null &amp;&amp; _hit.collider.tag == &quot;EnemyShipTag&quot;) {
  
          // We touched something!
  
          Vector2 target = new Vector2(_hit.collider.gameObject.transform.position.x, _hit.collider.gameObject.transform.position.y);
  
          const float moveTime = 0.1f;
          float step;
  
          step = Vector2.Distance(crosshairGO.transform.position, target);
          crosshairGO.transform.position = Vector2.MoveTowards(crosshairGO.transform.position, target, step / moveTime * Time.deltaTime);
  
          Vector2 _pos3 = new Vector2(this.transform.position.x, crosshairGO.transform.position.y);
          crosshairGO.transform.position = _pos3;
          crosshairBegin = false;
      } else {
          // Nothing hit
  
          Vector2 _pos2 = new Vector2(this.transform.position.x, 4.5f);
          if (crosshairBegin) {
              crosshairGO.transform.position = _pos2;
          } else {
              Vector2 _pos4 = new Vector2(this.transform.position.x, crosshairGO.transform.position.y);
              crosshairGO.transform.position = _pos4;
          }
      }
  
  
  }
  </code></pre>