Selecting Objects with Raycast – Unity Tutorial


I’m gonna show you how to use
physics-based ray casting in order to select objects in your game. My name is
Charles and this is infallible code a channel designed to help you become a
better game developer. If you want to learn more about game programming,
Unity, and game development then be sure to subscribe and hit that notification bell
icon so you’ll be notified every single time a new tutorial is made available.
I’ve created this very basic scene. It includes a simple environment, a UI, a
couple of objects, and an FPS controller. Why don’t we go ahead and press play. So
we can see that there’s a red dot at the center of the screen, and this is just a
part of our UI. And it’s gonna signify which one of our objects is selected. So
when the dot intersects with any one of these dark grey objects, we expect that
this object will be selected or selectable. Now typically you’d want to
allow the player to equip or use or pick up any of these objects. But to keep this
tutorial simple all we’re gonna do is just highlight these objects by
replacing this default material with a selected material. And we can preview
that really quickly by stopping the scene and going ahead and just dragging
one of these materials, the [email protected] material onto one of the
objects in the scene. And that’s just kind of a preview of what it’s gonna
look like once we have that red dot intersecting with the game object in the
scene. So it’s gonna look like this. Now since there’s multiple objects in the
scene we’re going to need to keep track of which one is selected and we’re going
to need to reset its material back to default when it’s deselected. So we’re
gonna need one script to manage all of the selections. That is going to be
called selection manager. So why don’t we go ahead and just create that now. I’m
going to create the script underneath my scripts folder and again I’m gonna call
it SelectionManager. Now I want to put this in the scene so I’m gonna go ahead
and create a game object and I’m going to call this game object the selection
manager, as well. And I’m just gonna reset its transform.
Once that’s in the scene we can drag the selection manager onto the object and
we’re ready to rock and roll. So why don’t we go ahead and open that up in
the code editor. We want the selection manager to update its selection each
frame so the first thing we need to do is implement the update method. Next
we’re going to want to cast a ray into the scene so I’ll create a new variable
called ray and let’s initialize it using the main camera. We’ll call screen point
to Ray and we’re going to pass in the current Mouse position. This is because
we’re using the FPS player controller so the center of the screen will always
correspond to the mouse position. Next we need to determine whether or not that
ray actually collides with any object in the scene. To that end we’re gonna use
the physics class and we’re gonna just check Physics.Raycast. If Raycast
returns true then we’ll know that it hit something. Now we need to pass in our
array that we just generated and we’re gonna need to pass a reference to a ray
cast hit object which I will create now all right so if physics dot ray cast
returns true then that hit object will be populated and we can use it to grab
the transform of the current selection perfect once we have the selection we
can go ahead and try to grab the selections render and if it has one then
we’ll go ahead and set its material to the highlighted material of course we
haven’t added the highlight material to our class so I’m gonna go ahead and add
it as a unity serialized field all right so we’ve got enough code here to test so
why don’t we just pop back into unity back in unity let’s select the selection
manager and let’s populate the highlight material I’m going to use the object at
selected material that I’ve created for this project if you download the project
it would be with the files all right perfect so
let’s press play and now when I look at my objects they should highlight very
nice oh except it’s not I guess it’s not deselecting so it’s staying highlighted
and on top of that if I accidentally look at the floor
looks like I’m swimming in a sea of piss not good so we need to do two things we
need to be able to deselect objects and reset their high light back or rather
their material back to their default material and we need to be able to
differentiate between objects that are selectable like our gray dark gray
objects and objects that are not selectable like the floor so let’s go
back into the code editor now okay so let’s tackle this one thing at a time
first I’m going to differentiate between selectable and non selectable objects
using a tag so I’m gonna add a serialized string field called
selectable tag and I’m gonna default it to selectable so any game object that’s
marked with the selectable tag will be selectable and in order to do that we’re
gonna need to add some new logic so let’s go down to our update method and
what I’m gonna do is after we determine the transform I’m just going to put an
if statement that checks the selections tag using compare tag and I’m gonna pass
in selectable tag and we’ll wrap the whole thing in brackets alright that was
easy enough next thing we want to do is deselect objects by setting their
material back to the default material so we should really just create another
serialized field here and I’m gonna call it default material and so in order to
deselect the current selection we need to actually keep track of the current
selection so I’m gonna add another private field that’s going to hold a
reference to the current transform that’s being selected all right so the logic for deselection
would looks a little something like this just the first thing we’re gonna do in
our and each update is check whether or not the selection field is no lore not
and if it’s not Noll we’re going to grab the selection renderer again set its
material to the default material and then set selection to null now you might
be looking at this and you might see this duplication here and I’m as tempted
as you are probably to refactor this but I’m going to just press on because you
never want to refactor too early once we finish the main functionality of this
class then I’ll go back and and wheel refactor this and we’re actually gonna
see that at the end of the video but for now let’s just press on so we have our D
selection logic but we’re not actually keeping track of the selection just yet
but that’s pretty easy we can just come down to that if statement that we just
added and at the end we can go ahead and say selection equal selection and there
we have it the code isn’t pretty and it actually is error-prone for instance if
that renderer is null when we set the selection that it’s gonna fail on D
selection but again we’re gonna worry about that sort of stuff later when we
refactor for now why don’t we just pop back into unity and ensure that the code
actually works back in unity we need to do two things first we need to actually
create a new tag called selectable so let’s do that now I’ll select add tag
add a new one call it selectable and of course we’re going to need to mark our
four objects as selectable then we need to go to the selection manager and
populate that default material again I’m going to use the object at default
material that’s included with the project if you download it and now we
can go ahead and press play so if we look at the floor awesome we’re
no longer standing in a pool of piss and if we look at any one of our objects and
look away we can see that all of our functionality is now in place we are
selecting and deselecting objects as expected so the code is complete and the
logic works but it’s kind of ugly so the next thing we’re gonna do is refactor if
you’d like to see that video then make sure you subscribe and turn on
notifications so you’ll be notified when it’s available thank you to all of my
patrons and the special shout out to dark rush photography and Zhi Richard
stands Sean Carey Thomas Wayne glows and Jakov

38 thoughts on “Selecting Objects with Raycast – Unity Tutorial

  1. 5:40 THing is, an object can only have one tag, right? Depending on the complexity of the code and systems, what about writing an empty Selectable class and replacing the tag == selectable tag with GetComponent<Selectable>() != null ? Would that be acceptable?

    Also, wouldn't it be better to save the currently selected object's default material in order to restore it once unselected?

  2. Use my coupon code to save 10% off the sale price of on-sale assets ⚡ CW2019AFF10

    https://assetstore.unity.com/?on_sale=true&orderBy=1&aid=1100l3e8M

  3. 5:41 According to Unity official document about Camera.main here https://docs.unity3d.com/ScriptReference/Camera-main.html :

    "The primary Camera in the Scene. Returns null if there is no such camera in the Scene. This property uses FindGameObjectsWithTag internally and doesn't cache the result. It is advised to cache the return value of Camera.main if it is used multiple times per frame"

    Then I think we should better cache the reference to Camera.main at Start() instead of call Camera.main in Update() loop

  4. Great video as always Charles! Setting the layermask when Raycasting results an increased performance, right?

  5. Better to just save the default material from the object itself before changing it. This would allow you have different material for each object.

  6. I wonder if you could get around some of those awkward null check statement using some null propagation from C# 6.

  7. Dear… please can you help me with this issue as you are great dev .Why when im trying to download Unity after completing its showing error cod 2 which is saying file location not found even i determined the download location or its mean something else.

  8. It's a pity Unity's input system is so convoluted as this kinda should be implemented as an input system raycaster so you can just hook into the existing event lifecycle with IPointerEnter etc. Had to do this for Magic Leap recently but the actual implementation of Event System Raycasters is messy.

  9. How do I add a red dot? I made a script with a Raycast, everything works fine but the only element missing is the red dot and I have no idea how to incorporate it in my game. Thx bud

  10. hello thanks for making this tutorial I have made a canvas instanter for select some object and instantiation canvas for visualization projects but I am first making a code please help me for about Thank you soo much

  11. it's complicated, not for beginners,
    I highly recommend the tutorials official Unity, clearer, simpler, more relevant

  12. I'm really confused about something.

    When we hover over a Selectable object, _selection grabs that information.
    So before we even deselect the object, isn't it true that _selection != null ?
    Therefore, shouldn't it be resetting to defaultMaterial and back to highlightMaterial over and over while we're hovering our mouse over the object?

    I must be missing something here. 🙁

  13. men i have some problems, i make some GameObjects and save them as prefab item, but i can select them, its like the raycaster dont recognise them or can find them, i put a print to see some in console, but nothing appear so, have any idea about that?

  14. Y para cuando es en 2D para teléfonos con Android como es para seleccionar un GameObject entre todos los que tengas colocados en tu Scena

  15. You can use raycast for a hearing system too. I mean, a enemy isn't able to hear the player that well in a room with a wall in between them.

  16. hi Charles, can you help me in calling a function by focusing the raycaster on a particular object

    Thanks in advance

  17. Note: Input.mousePosition may not consistently produce an accurate coordinate for the center of the screen. Instead, you can use "new Vector3(Screen.width/2f, Screen.height/2f, 0f)" where "Input.mousePosition" would be to get accurate results.

    (Unity has acknowledged this bug and has stated that they are not going to fix it, as it is part of the legacy Input system which is currently in the works to be replaced entirely. )

  18. Hi Charles. Great tutorial.
    I have created a script, where I want to cast a physical raycaster from the Oculus VR headset and interact with a few objects I have made interactable.
    I my code I have OVRCameraRig where I want the physical raycast to shoot from, but for some reason it doesnt work? Can you or anyone here help me? 🙂
    I will gladly post the code. I saw here that you use Camera.main, but what if I want to use OVRCameraRig? How can I make that possible?

  19. Hey! I have a question – what if I want multiple various default materials, can I add multiple tags and for each one there's going to be another default? If it's possible, how to code it properly so that it doesn't report some errors?

  20. i gotta question.
    If i want that raycast to be shorten: i mean you have to be near of an object (range) to be able to select it as you do on the video, how can i do it?
    Thanks!

    PD: ok found a solution and it worked! Thank you anyway mate 😀 liked it

Leave a Reply

Your email address will not be published. Required fields are marked *