Start coroutine on a target hit by a raycast ?

Hello there, I’m currently struggling with the following issue :

I am using a raycast to interact with gameObjects in my game, basically saying “if they are in range and you press E interaction time”; however I am currently attempting to make it so that upon pressing interact, the object hit by the raycast, which will always have a certain script, start a coroutine.
However I find myself unable to do so. Any help would be much appreciated.

Is there perhaps a way for the gameobject to detect if he is being hit by a raycast ?

If you need any further information in order to assist, feel free to ask them and I’ll do my utmost to answer as best I can.

On the object being hit:

public void StartDoingSomething() {
  StartCoroutine (MyCoroutine());
}

In the raycast code:

if (Physics.Raycast(..., out RaycastHit hit)) {
  hit.collider.GetComponent<MyScript>()?.StartDoingSomething();
}

Obviously replace the names of things with your actual script and method names.

How are you performing your raycast? When a raycast is performed, you have a parameter for a Raycasthit, that variable will provide information on what it has hit. From that, you can look for the class on the hit object and call a method on it if it is there.

You can output the results of a Physics.Raycast to a RaycastHit, which contains the Collider & Transform reference of the object it hit. From there, you can reference the GameObject by either using collider.gameObject or transform.gameObject, followed by GetComponent to get the script on that object you’re looking for, and finally, starting a coroutine on that script.

Example:

public class SomeScript : MonoBehaviour {
   public void DoTheThing() => StartCoroutine(TheThing());

   private IEnumerator TheThing() {
      //etc...
   }
}
public class SomeOtherScript : MonoBehaviour {
   void Raycast() {
      RaycastHit hit;

      if(Physics.Raycast(/*etc..*/)) {
         if(hit.transform.gameObject.TryGetComponent(out SomeScript someScript)) {
            someScript.DoTheThing();
         }
      }
   }
}

(If you’re not familiar with TryGetComponent, see the docs: Unity - Scripting API: Component.TryGetComponent)

Thank you very much for the answers, I’ll be sure to try them out as soon as I can !