Checking if an object has an ancestor with certain tag

I want to check to see if a collider that is hit is the descendant of any of the objects with a specific tab, to decide what kind of particles to emit. I can’t just go through every object in the game with that tag, because there may be several hundred of these objects at a time, and there will be several tags. Also, each object has multiple colliders at different depths in the hierarchy.

function HasParentOfTag( tag : String ) : boolean {
  var check : Transform = transform.parent;

  while ( check ) {
    if ( check.CompareTag( tag ) ) return true;
    check = check.parent;
  }
  return false;
}

It’s probably best to store that result during runtime rather than call the function a lot, since it won’t exactly be super fast.

With a slight modification (I’m calling from another script, not the object), it works very well.
Thanks!