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.
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...
}
}