# Raycasting question

Hi! I was wondering if it is possible to instantiate an object at the end of a raycast if it doesn’t hit something (or if it isn’t easily possible, instantiate where the end of the ray would be). Any help would be appreciated.

P.S. I checked the manual and API for raycasting, I can’t really figure it out

Yes, it is. I mostly copied the sample from Physics.Raycast:

``````Vector3 fromPosition; // set this to wherever you want to cast from
Vector3 direction; // set this to your direction
float distance = 15f;
if (Physics.Raycast(fromPosition, direction, out hit, distance, layerMask))
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
Debug.Log("Did Hit");
}
else
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
Debug.Log("Did not Hit");
Instantiate(somePrefab, fromPosition + distance * direction.normalized, Quaternion.identity);
}
``````
1 Like

Okay, thanks a lot, man. I’m running a bit late on my project and you just made the game a whole bunch more playable

Error being thrown: “The name ‘direction’ does not exist in the current context”

Do I need to be using any additional namespaces, or is VS just being VS?

Please don’t just copy and paste.

In line 2, direction is declared… I don’t know the position and direction in which you want to cast, so that’s up to you. The takeaway for the question of how to spawn an object “at the end of a raycast” is another question: Where is the end of a raycast? In case of distance == Math.Infinity, there is none. In case of a finite distance, you can calculate it like this:

``````Vector3 endOfRaycast = position + direction.normalized * distance
``````

RIGHT I FORGOT THAT DIRECTION WAS A VARIABLE. Derp.

thank you so much im in a game jam and have less than a day left