Detecting if Raycast's current hit is different from the previous hit

Hi, all!

My code below demonstrates showing the name of the object currently hit by the raycast (as soon as the cursor meter is full)

if (Physics.Raycast(transform.position, transform.forward, out hit)
{
     _cursorFill.fillAmount += 0.05f;
    if (hit.collider && _cursorFill.fillAmount == 1.0f)
   {
       objectName.text = hit.collider.name;
   }
  else
  {
      objectName.text = "";
  }
}

My problem is, some of my 3d objects in the scene sit too close together. When I look from one object to another, i no longer get the loading effect (since the fill amount is already equal to 1.0f), it just straight up changes the name. I need help modifying my code so that every time the raycast detects a different object from the previous one, the loading before showing up the name restarts.

Store previous collider, and check if the collider is different one.

private Collider _prevCollider;

// Raycast
Collider hitCollider = hit.collider;
if (_prevCollider != hitCollider) {
    // Do your text logic;
}

_prevCollider = hitCollider;
1 Like