Get Object from Mouse Click and Call Functions through Interface 2D & 3D - Unity Tutorial

  Рет қаралды 40,483

samyam

samyam

Күн бұрын

Learn how to use raycasts to click on objects with your mouse, and then make then execute functions via interfaces! I show how to do it in both 2D and 3D!
ᐅGet the full Source Code Bundle to my Unity Tutorials 🤓
sam-yam.itch.io/samyam-full-s...
📥 Get the Source Code 📥
/ get-object-from-41358553
🔗 Relevant Video Links 🔗
ᐅPrevious Video - Custom Cursor with Input System - Unity 2020 Tutorial:
• Custom Cursor with Inp...
ᐅCoin Animation
opengameart.org/content/coin-...
ᐅKenney's Game Icons (expansion):
www.kenney.nl/assets/game-ico...
ᐅForest - Low Poly Toon Battle Arena / Tower Defense Pack
assetstore.unity.com/packages...
ᐅCustomizable skybox
assetstore.unity.com/packages...
🤝 Support Me 🤝
Patreon: / samyg
Donate: ko-fi.com/samyam
Disclosure: This post may contain affiliate links, which means we may receive a commission if you click a link and purchase something that we have recommended. While clicking these links won't cost you any money, they will help me fund my development projects while recommending great assets!
😎 Cool Unity Assets 😎
ᐅPeek - Editor Toolkit: assetstore.unity.com/packages...
ᐅEditor Console Pro: assetstore.unity.com/packages...
ᐅRainbow Folders 2: assetstore.unity.com/packages...
⏱️ Timestamps ⏱️
0:00 Intro
0:44 Recap
1:17 Set up Ray
3:55 Click 3D Objects
7:45 Click 2D Objects
10:40 Interfaces for Calling Functions
💖💖THANK YOU TO ALL MY PATRONS 💖💖
❯❯❯ My Links ❮❮❮
💗 Patreon 💗
/ samyg
💬 Discord Server 💬
/ discord
🐦 Twitter 🐦
/ samyam_utube
📚 Facebook 📚
/ samyam.youtube
🎵 Music 🎵
Fretless by Kevin MacLeod
Link: incompetech.filmmusic.io/song...
License: creativecommons.org/licenses/b...
👍 Like and Subscribe! 👍
🖥️ Computer Setup 🖥️
*As an Amazon Associate I earn from qualifying purchases.
www.amazon.com/shop/samyam
#unity3d #unitytutorial #gamedevelopment

Пікірлер: 82
@pleasedontsub2732
@pleasedontsub2732 2 жыл бұрын
the fact that you show how to do it in both 3D and 2D shows dedication and that you really want to bring out good content for people trying to learn game design. I love that. You just earned a subscriber.
@samyam
@samyam 2 жыл бұрын
Thank you so much :)
@cjc813
@cjc813 2 жыл бұрын
Just wow. You (a) showed the code, (b) explained the ideas/functionality behind the code, (c) referenced the relevant documentation, and (d) were clear in your explanation. Most coding tutorials *might* do like 2 out of 4. Thanks. :)
@gurfotron7
@gurfotron7 3 жыл бұрын
These videos are really great thank you. The focuses are all very practical and your explanations/breakdown are easy to follow.
@_olives
@_olives 3 жыл бұрын
Your tutorials are all super helpful!!
@CasterTechMo
@CasterTechMo 3 жыл бұрын
all I did was skim your video to see if it was what I needed and I can already tell this is a better tutorial than 90% of anything else iv found on youtube. I really appreciate that you took the time to show how to not only make specific responses based on what you click but also how to do it in both 2D and 3D. YOU GOT A NEW SUB!!!
@samyam
@samyam 3 жыл бұрын
Yay! Awesome 😄
@patnev9296
@patnev9296 2 жыл бұрын
Awesome video, love the editing, explanation and pacing of it. Clear and easy to follow :)
@samyam
@samyam 2 жыл бұрын
Glad to hear! 😄
@kuumaaa
@kuumaaa 3 жыл бұрын
thanks very helpful, had some trouble with raycasts and how to correctly interact with the interface. exactly what i was looking for
@fateshow5303
@fateshow5303 2 жыл бұрын
super clear and simple to follow, really great!
@samyam
@samyam 2 жыл бұрын
thanks!!
@mrtaluspa9903
@mrtaluspa9903 Жыл бұрын
ohh thanks! you helped me so much
@fabioecco
@fabioecco Жыл бұрын
Great video!👏
@quinzelbeck
@quinzelbeck Жыл бұрын
Wow, this is an amazing tutorial, im searching for a fast answer because im doing something for a jam, but the explenation makes me to watch all
@aslightlyovergrowncactus3315
@aslightlyovergrowncactus3315 Жыл бұрын
Thanks! I'm a beginner at Unity and this was really helpful!
@samyam
@samyam Жыл бұрын
glad to hear!
@tessacarstairs5998
@tessacarstairs5998 2 жыл бұрын
thank uuuuu! xD
@HadiLePanda
@HadiLePanda 3 жыл бұрын
Great tutorial as usual, really like the format with the recap ^^ That keyboard's clicky sounds made the video go from 10/10 to 11/10 haha, which keyboard is it?
@samyam
@samyam 3 жыл бұрын
Thanks 😂 The Logitech G815 Clicky keyboard
@Satscape
@Satscape 3 жыл бұрын
Congrats on 1K subscribers! They may have fixed this by now but, RaycastAll() may not return colliders in the order that they were hit, as I found out fairly recently... D'OH!
@samyam
@samyam 3 жыл бұрын
Thanks! And nope it's still unordered 😂
@blankii6762
@blankii6762 8 ай бұрын
Thank you very much!
@danniton9831
@danniton9831 2 жыл бұрын
3:01 - 3:49 For those who wants to do this in a much easier and simpler way. Just write "Input.mousePosition" instead of "controls.Mouse.Position.Readval.........." this way, you can skip all that setup in the time stamp.
@samyam
@samyam 2 жыл бұрын
Or for the new input system you can use using UnityEngine.InputSystem; ... Vector2 mousePosition = Mouse.current.position.ReadValue();
@itookaonabookanyway7385
@itookaonabookanyway7385 Жыл бұрын
@@samyam I'm too lazy but does it have a performance improvement over Input.mousePosition?
@kaloshabuthapa3284
@kaloshabuthapa3284 2 жыл бұрын
I have a third person and first person camera. What changes do I need to make to the code?
@g.nath0
@g.nath0 Жыл бұрын
11:26 I got a problem with "hit" in lines 106,107 says CS0103: The name 'hit' does not exist in the current context. What I missed
@ariehuybregts9875
@ariehuybregts9875 3 жыл бұрын
Great tutorial, I really appreciated all the options, does the clicked function need to be public because of some characteristic of interfaces, or is it just so that it can be called from the mouse script?
@samyam
@samyam 3 жыл бұрын
All functions in an interface are public by default, since they are meant to be called jeremybytes.blogspot.com/2019/11/c-8-interfaces-public-private-and.html?m=1
@ariehuybregts9875
@ariehuybregts9875 3 жыл бұрын
@@samyam thanks for the response, and that blog post is really interesting
@donnyhudson4196
@donnyhudson4196 3 жыл бұрын
Awesome vids!!! Thanks. Was wondering how I might run something in the OnClickAction that might need to be in an FixedUpdate? Like moving a Rigidbody in a Parent when I click on a button.
@samyam
@samyam 3 жыл бұрын
The interface is just like a recipe for the script implementing it, so you can call it anywhere in the same way. But in this case do you need an interface for a Ui button? You can just implement the OnClick function for the UI button. Also, once you click the button you can set some values if you are doing a continuous moment, if buttonpressed, movementup = 1 as an example. If it’s a continuous movement I recommend using an On Screen Button which is perfect for this occasion and pipes the value into a certain control you can then call. If it just needs to move to a certain location you can use a coroutine that starts once the button is pressed and ends once it reaches its destination. Hope that helps :)
@donnyhudson4196
@donnyhudson4196 3 жыл бұрын
Thanks for the fast reply. I've never used interfaces before...they seem interesting and usful. I built my own pirate ship and it has a couple buttons with colliders on a console...for moving the ship via a rigidbody. Forward button...stop button and reverse button. Forward button I wanted it to move smoothy forward at a constant speed...stop = no motion and reverse opposite of forward. I may be in over my head...lol. I'll have to read your reply over a few times. Also my first indever into this much physics. Player has a rigidbody also. Thanks again. It amazes me how much knowledge you have 💯👍
@donnyhudson4196
@donnyhudson4196 3 жыл бұрын
I did something last night that made the ship jump forward "not smoothly" lol. Then my player slid off the back of the boat...he doesn't move with the boat...lol. I'm seeing from searches this whole senerio may be perty difficult 🤔 Here's the script I put on my forward button so far. I'm just a beginner...lol. To make the ship move at a constant continuous speed until i hit the stop button it would have to be in the fixed update somehow right? public class Forward : MonoBehaviour, IClicked { public float speed = 10; public Rigidbody rbBoat; public Rigidbody rbPlayer; public void onClickAction() { // This makes the ship jump forward but only one quick jump rbBoat.velocity = transform.forward * speed; } //This makes the player shoot straight up in the air...lol private void FixedUpdate() { FollowShip(); } public void FollowShip() { rbPlayer.velocity += rbBoat.velocity; } }
@samyam
@samyam 3 жыл бұрын
Yeah physics objects should be moved in FixedUpdate, also try using MovePosition function for moving rigidbody instead docs.unity3d.com/ScriptReference/Rigidbody.MovePosition.html
@Gnenguin
@Gnenguin 3 жыл бұрын
You are an absolute fucking legend 💪
@TheKr0ckeR
@TheKr0ckeR 2 жыл бұрын
I mean I checked everywhere for clear 2d raycasting tutorial and this explains it in a best way! Plus, I have a nice example with interfaces now. Thank you. I think you can get more attractions if you add "Raycasting 2d/3d" with the title. :) Here is a question: After we select our object, I want to click some object and want it to go there. What way should i follow for that? I mean I can get the info of clicking now, but only clicked object should go there. :)
@samyam
@samyam 2 жыл бұрын
Thanks! I've added 2d in the title. Do you mean clicking 2 objects in a row? Well you'd need a manager or some script to store the currently clicked object, and then on the second click check if there's already a clicked object, and if there is, move to the location.
@TheKr0ckeR
@TheKr0ckeR 2 жыл бұрын
@@samyam Great! I'll do that with the new input system. So maybe i can create a temporary gameObject variable, and i can assign the "clicked" object to that. then i can do whatever i want? Is that true way to go or are there any better ways, I dont know how to check second click
@samyam
@samyam 2 жыл бұрын
That’s one way! Or you can use an interface and implement it on your gameobject, then use the position that was clicked and move there (you can pass the position through the interface or just read the mouse value separately)
@TheKr0ckeR
@TheKr0ckeR 2 жыл бұрын
@@samyam Like we did in the video? My game is cafe game that we a waitress, so we first click a waitress, then if it is selected, i click on table and waitress go there, for that scenario ,I should implement the interface on "table"? I couldn't understand the second logic, because i have already IClickable interface like we did in video! Thanks btw'
@chris.davidoff
@chris.davidoff 3 жыл бұрын
Sweet video! The only thing I'd criticize is the example of non alloc. You're still allocating and destroying your raycast hits in your example. To make use of non-alloc, you should allocate the hits array as a private or public variable, in order to avoid the garbage collection
@samyam
@samyam 3 жыл бұрын
Great point! Slipped my mind for the tutorial 🙂
@chris.davidoff
@chris.davidoff 3 жыл бұрын
@@samyam Woah! Thanks for the pin :) and no worries, I'm trying to make my own tutorial and it's hard!!
@luisalbertoherrera5439
@luisalbertoherrera5439 3 жыл бұрын
Great tutorial! How can I do this with an android project? I was thinking that I could reemplace or add something in the beding for reemplace the right clic to a touch action...
@samyam
@samyam 3 жыл бұрын
It's very similar but you would use the touch position in the input action to track the position and the touch contact to tell if there is something touching the screen (video on that coming soon)
@luisalbertoherrera5439
@luisalbertoherrera5439 3 жыл бұрын
@@samyam thank you for your response I will wait :)
@doodlebugdev6990
@doodlebugdev6990 Жыл бұрын
It keeps saying cameraMain does not exist for Ray ray = cameraMain.ScreenPointToRay;
@paganotommaso
@paganotommaso 2 жыл бұрын
Is there a method to make it on mobile? Because I don't want to create a custom cursor
@samyam
@samyam 2 жыл бұрын
This should work without the custom cursor, and just replace the mouse coordinates with touch coordinates
@paganotommaso
@paganotommaso 2 жыл бұрын
@@samyam thanks!
@drawfulanimations
@drawfulanimations 3 жыл бұрын
I'm going through this tutorial and everything works for me until I try to use the interface. Unity says this: "error CS8701: Target runtime doesn't support default interface implementation." I've tried to figure out what's wrong and how to fix it but It doesn't make sense.
@samyam
@samyam 3 жыл бұрын
What .Net core version does your project use? Try using the latest version
@rajveermishra8713
@rajveermishra8713 3 жыл бұрын
For me I have an error that controls at line 66 is being used wrong and idk how to fix it pls hel
@samyam
@samyam 3 жыл бұрын
Can you post the exact error code and that line of code here?
@rajveermishra8713
@rajveermishra8713 3 жыл бұрын
I found a different video but I'll still do it
@noone-rh7pd
@noone-rh7pd 2 жыл бұрын
hello can you make a video on how to make a text appear when clicking on an object cause i've been looking all over for a solution and yours is close to what i want but i cant make it work yet
@samyam
@samyam 2 жыл бұрын
The concept should be the same as in this video, once you click on something check if it has the interface, and in your case make some text appear if it is clicked
@noone-rh7pd
@noone-rh7pd 2 жыл бұрын
@@samyam thanks i worked on it although i have a new problem I have this computer in my game and i want to connect it to other objects for example i dont want the other object clickable until i turn them on from the computer any idea how it works??
@samyam
@samyam 2 жыл бұрын
You can either have a manager keep track of what objects are connectable or have each individual object keep track of if they are connected. Then your interface implementation can check if the object is connected and do something with it.
@gejohans
@gejohans 16 күн бұрын
I am an elderly lady who wants to create a game. And this is the best guide I've seen for Unity. I hope they pay you!!! But I have a question. Suddenly in the film I see two new scripts. "Coins" and "Tower". I assume they are included from the Asset package. But I create my own "package". Should I have a script for each and every thing I click on that I want to do something with? Can they be in same script? How do I connect those scripts to my main script? How do they find each other?
@gejohans
@gejohans 16 күн бұрын
Um ... or ... is that the interface ??
@gejohans
@gejohans 16 күн бұрын
I got it. This is good.
@samyam
@samyam 15 күн бұрын
Nice, good luck! Here’s our Discord if you’d like to join. You can ask for help in the #help channel discord.gg/EyCzPbP5Gw
@anglevertex1781
@anglevertex1781 3 жыл бұрын
How do I acces the mouse controls menu?
@samyam
@samyam 3 жыл бұрын
Do you mean the input action asset we created? It should be somewhere in your assets folder, wherever you created it.
@jthale7381
@jthale7381 2 жыл бұрын
Thanks, this was awesome! Have a coffee on me.
@samyam
@samyam 2 жыл бұрын
Hey JT Hale aw thank you so much! That's super appreciated
@SaSeshen
@SaSeshen 3 жыл бұрын
Have you done a tutorial on how to make movement possible by using the new input system and clicking on the map? I don't mean the isometric tile map, because that is limited to the tile map, but to use it in a generic form that has a mesh, or collider so that you can ray cast your intended move position by right clicking. Essentially, if that made no sense, or if that was wrong, how do you make a movement system like League of Legends, where all movement is just clicking on the screen?
@samyam
@samyam 3 жыл бұрын
I haven’t made a video on that yet, but it should be very similar to what I showed in this video. I’ll add that to my list of potential future videos!
@SaSeshen
@SaSeshen 3 жыл бұрын
@@samyam I figured as much and I was able to replicate it somewhat, but the issue is that with the mouse Position or Delta, it doesn't initiate solely on a click, but is a constant activation, anytime the pointer moves. I am struggling to get the silly thing to ONLY work on a click, and setting the interaction to press only, only makes the code work once, when you click on the game tab. I am missing something very simple I am certain but that is why I am asking haha. Of course, the solution exists in spades with the old input system, but the point of using the new input system, is to not have to rely on the old one, as it more data intensive... that and I am trying to learn how to do this stuff "the correct way" using modular coding techniques. DOTS and ECS though... not sure I am quite ready for that since it is relearning, and reapplying Unity C# which I am already struggling with haha.
@samyam
@samyam 3 жыл бұрын
I would suggest using the performed callback for that action so you can call a function only when the mouse button has been pressed Example at around 6:00: kzfaq.info/get/bejne/j5dyhNJy0rqnYqc.html
@ahmetfirat23
@ahmetfirat23 3 жыл бұрын
I don't understand how you reference cursorcontroller. When I write the same vs says create a new class.
@samyam
@samyam 3 жыл бұрын
What are you referring to with cursor controller?
@ahmetfirat23
@ahmetfirat23 3 жыл бұрын
@@samyam controls variable at 5:18 controls.mouse.position line.
@alphaanar2651
@alphaanar2651 3 жыл бұрын
l see there great opportunity to make guns for MMORPG
@samyam
@samyam 3 жыл бұрын
How do you mean?
@alphaanar2651
@alphaanar2651 3 жыл бұрын
@@samyam if you click to the enemy enemy can get damage
@samyam
@samyam 3 жыл бұрын
Yeah that's a potential use case! Or any type of resource management game too
every step to actually make your dream game (then sell it)
24:27
Alat Seru Penolong untuk Mimpi Indah Bayi!
00:31
Let's GLOW! Indonesian
Рет қаралды 16 МЛН
Мы никогда не были так напуганы!
00:15
Аришнев
Рет қаралды 6 МЛН
3M❤️ #thankyou #shorts
00:16
ウエスP -Mr Uekusa- Wes-P
Рет қаралды 14 МЛН
choosing a game engine is easy, actually
15:08
samyam
Рет қаралды 327 М.
The Power of Scriptable Objects as Middle-Men
17:41
samyam
Рет қаралды 119 М.
Unity Tutorial | Clicking and Dragging 2D Sprites
11:00
I Wish I Had Known This Before I Started Unity Game Development...
11:11
A new way to generate worlds (stitched WFC)
10:51
Watt Designs
Рет қаралды 515 М.
The comments on my game were interesting....
9:00
samyam
Рет қаралды 16 М.
How to get Mouse Position in 3D and 2D! (Unity Tutorial)
10:20
Code Monkey
Рет қаралды 136 М.
When you FULLY AUTOMATE mathematics...
29:47
Real Civil Engineer
Рет қаралды 259 М.
How I made an Excellent Platformer
8:25
GoldenEvolution
Рет қаралды 260 М.
Косички из морковки 🥕
0:40
Сан Тан
Рет қаралды 8 МЛН
The screw cap can also be played like this
0:20
Dice Master_1910
Рет қаралды 13 МЛН
Он просто решил сэкономить на плитке, но...
0:25
Всегда проверяйте зеркала
0:21
Up Your Brains
Рет қаралды 4,3 МЛН
Who has won ?? 😀 #shortvideo #lizzyisaeva
0:24
Lizzy Isaeva
Рет қаралды 50 МЛН