1

I was going through few tutorials and came across Raycast while one used Instantiate to fire a gun and the other used Raycast. I've been programming for a while and I'm still unsure whether I should use Raycast or the latter. Can anyone explain me how it works.

1
  • You might use a Raycast to check where your bullet might go if fired in a certain direction. You could fire a bullet by Instantiating one at your gun's location. Two different approaches, you decide what's best for your game. Commented Nov 4, 2018 at 19:17

1 Answer 1

4

Quite a big difference. Actually, they couldn't be more different, but I can see the confusion if the first time you learn about them is from the use of firing a gun.

Raycast: Imagine a laser. You pick a start point and a direction of this laser and then it returns where the laser hits.

Instantiate: You can't really compare this with raycasting at all. Unity uses things called GameObjects. The player is a GameObject, the camera is a GameObject, the terrain is a GameObject. Instantiate() simply creates a new GameObject.


Using Raycast() to fire a gun is pretty straight-forward; start point is the position of the gun, give it the direction, then you get where the gun hits. Using Instantiate() to fire a gun would mean creating a GameObject called "bullet" with a RigidBody and a Collider. It would be more performance-intensive but you could add things like bullet drop, wind, ricochet. Although, you might still need to use Raycast() to make sure it doesn't go through anything between physics updates, since it's probably moving very fast.

Next time, you should use the Unity Manual for a question like this.

First thing that came up in Google for "Unity Instantiate" and "Unity Raycast".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.