Raycast Shooting in Unity!

Marcus Ansley
2 min readAug 16, 2021

--

Let’s take a look at how we can add a raycast ‘shooting’ system in Unity 😉 You may want to keep this code within our previously-created Player class, or you might want to house this in a dedicated ‘Shoot’ class (which is what I’ll be opting for this time).

Objective: Create a raycast ‘shoot’ system, so that whenever the player left clicks they fire a ray from their mouse position (the center of the screen) towards an object in the scene.

1. Firstly, we’re going to want a reference to the main Camera in the scene. We could just use Camera.name and use this in any calculations we need to make, or we could store this in a dedicated Camera variable within our script. If we opt for the latter, we’ll most likely need to initialise this variable within our Start method:

2. Next let’s create a ‘Fire’ method. We’ll need to declare both a RaycastHit and a Ray variable: one to store information about anything we hit, and the other to actually represent the ray itself. For the ray, we’ll need to assign the following to it so that it knows where we’re firing the ray from and the direction we’re firing it in: ‘Camera.main.ScreenPointToRay(Input.mousePosition)’. We’ll then need to perform an if check on this, checking to see the result of this raycast and review the information received from it. For the time being, we can store the Transform of the object hit using hit.transform, and can print the name of this object to the console using hit.transform.name. Here’s how our code’s looking right now:

3. All we need to do is call this Fire method appropriately (i.e. from the Update method whenever the player left clicks). If we add that in, we should be good to test this out in Unity:

That’s all for now, but we’ll return to actually inflicting damage on objects (specifically Enemies) at a later stage. We’ll most likely be retrieving an Enemy script off the object (if there is one) and calling a public Damage method😉

--

--