✅ Get the Project files unitycodemonkey.com/video.php?v=LdoImzaY6M4 🌍 Get my Complete Courses! ✅ unitycodemonkey.com/courses 👍 Learn to make awesome games step-by-step from start to finish. 👇 Click on Show More 🎮 Get my Steam Games unitycodemonkey.com/gamebundle POLYGON - City Pack cmonkey.co/synty_city_talknpcs POLYGON - Heist Pack cmonkey.co/synty_heist_talknpcs Basic Motions Animations assetstore.unity.com/packages/3d/animations/basic-motions-157744?aid=1101l96nj&pubref=talktonpcs 🔴 RELATED VIDEOS 🔴 Why you should NOT make everything PUBLIC! ruclips.net/video/pD27YuJG3L8/видео.html Simple Chat Bubble in Unity! (Chat, NPC, Multiplayer) ruclips.net/video/K13WnNL1OYM/видео.html Kickstart your game with First and Third Person Controllers! (FREE Unity Starter Assets) ruclips.net/video/jXz5b_9z0Bc/видео.html Make your Animations DYNAMIC with Animation Rigging! ruclips.net/video/LEwYmFT3xDk/видео.html SMOOTH with LERP! (Move, Rotate, Float) ruclips.net/video/jAN2IoWdPzM/видео.html What are Interfaces? (C# Basics) ruclips.net/video/MZOrGXk4XFI/видео.html
PLEASE ANSWER ME ! why do I keep getting this error message in the console -ArgumentException: The Object you want to instantiate is null. UnityEngine.Object.Instantiate[T] (T original) (at :0) GamePrefabAssets.get_i () (at Assets/Asset_Game/Test_Stuff/ChatBubble/GamePrefabAssets.cs:16) ChatBubble.Create (UnityEngine.Transform parent, UnityEngine.Vector3 localPosition, ChatBubble+IconType iconType, System.String text) (at Assets/Asset_Game/Test_Stuff/ChatBubble/ChatBubble.cs:15) NPCInteract.Interact () (at Assets/NPCInteract.cs:13) PlayerInteract.Update () (at Assets/PlayerInteract.cs:24) - I did everything like you 5 times, I went through all the video clips that are needed for this, created chat bubbles. However, I keep getting this message, why?
15:55 Optimization tip for the distance checking part: - Vector3.Distance involves a square root in the math, which is super slow to compute. Since you're only checking which object is the closest, you can use squared distances to remove the square root and make the check faster. - There's no Vector3.SquaredDistance static method, however you can use (pos1 - pos2).sqrMagnitude. This returns the squared distance between pos1 and pos2.
I learned the hard way about this performance tip ages ago, the workaround you posted sounds neat and I'll make sure to give this a try soon. Much obliged.
That was true many years ago, but now there is no real measurable difference in using Vector3.Distance compared to sqrMagnitude. See Tarodev's channel and his video "Unity Code Optimization - Do You Know Them All?"
@@slygamer01 I read something similar when I was looking through this yesterday, as I figured the best way to optimize Distance would be to settle for the Q3 Fast Inverse Square Root function. What I found was a few measurements showing that the difference was negligible, as well as the usual smug nonsense of a Unity forum war. It proved to be rather amusing up until it wasn't.
I really must be getting better at this coding thing because the whole video I was like, "This code is neither nice or clean, why isn't he using an interface!" You got me good CM! Cheers!
Oh man, I was stumbling my way through basically this very thing, but started with object interaction and was going to use it as the base for my NPC conversations. But then you come along and show off the right way to do it. Thanks! Now I get to go fix everything I did wrong.
for YEARS i've struggle to understand Interfaces. two senior devs tried teaching me for days, ive looked to yt videos and never got it quite right. until this video and your simple and amazing explanation. thanls SO MUCH for this!
Fantastic teaching. I've watched enough of your videos to anticipate we'd get to interfaces, but buildup (showing the scaling issues and the solution) is a fantastic teaching method.
Conspiracy: Code Monkey is an angel of knowledge, set to test humanity's willingness to pursue knowledge. Part of a way he tests is to remove the "I don't know what to do next" excuse by always providing ways as the needs arise.
At 24:46, instead of checking proximity to NPCs and taking the closest, this has a potential problem where you are standing between the two, closer to Alice, but are facing Bob and want to talk to Bob. In this case it will still give you the wrong interaction. I personally would calculate the angle-difference between player-forward vector and vector from player to NPC, and take the one with the smallest angle difference. (i.e. calculating in code, the answer to the question "which one am I facing?")
Excellent video! Covered some great topics, demonstrated them in a clear and thorough manner, and the visuals and initial setup of the project are beyond the normal tutorial grade. Great work :)
I actually encountered this problem many times in the past. What I think is a good solution is making an npc component which inherits an interactable interface. Your solution is great too and I really enjoyed the video. Keep it up
At the beginning of the video, I immediately thought about interfaces and was surprised that you ignored them... but in the end you corrected yourself... And by the way, your explanation of interfaces for beginners is impeccable )
Loving the vids and how you break down the logic for further additions and improvements. I'd be keen to see you possibly do a tutorial on an Anno style system with automated NPC pathfinding to new buildings / task finding etc - Unless you have something similar already
For recalculating path you would probably just have the Pathfinding system fire off an event when the pathfinding map changes (like when a new building/road is placed) then have the unit listen to that event and request a new path. I made a nice Task System a long time ago which I used in my game Battle Royale Tycoon unitycodemonkey.com/video.php?v=rQXr9XTu6CI
Dude your tutoriales are VERY good and informative. My only problem now is deciding which of the like 7 ideas I have for games I should start making into a complete one lol
I found myself in a similar situation earlier. For me I decided to make the easiest of them first. So I can finish it move on to the next.But in my case the second and maybe even the third idea is like an extension of the first so i can reuse and repurpose a lot of it. you could say they happen in the same universe or whaterver. If i will finish any of it is yet to be decided.. lol. You could also approach it in way like "which game benefits you the most?"
Hey Codemonkey. So this was one of the hardest problems I've ever had to figure out and I succeeded without the physics.overlap function. I did run into it during research but failed to see how I could effectively use it. I see now how useful it would have been in my situation, I might still go back and swap my method for yours if it becomes too unweildy. I ended up adding an interact script to every interactable item which then each tracks the distance from itself to the player so it knows when to pop up the UI banner. I will definitely use this video as reference, there is hardly anything out there on this subject, thank you.
That approach is less efficient but depending on how many Interactable objects you have it might not necessarily be a problem. If you come across performance issues in the future then that could be an easy way to get a few more fps
Best video I've seen in about NPCs on RUclips by far, however as a very new game developer (if you can call me that), I feel you should have made the video tutorial without referencing code from another video. The chat bubble concept as well as the rigging concept are wonderful and amazing, however if the goal is to be easy to follow, the tutorial should 100% be independent of other skills other than the ones showed in the video. I quite frankly feel really discouraged to continue with this tutorial because it requires me to learn and apply two more unity tutorials, which are the skills and knowledge revolving around the chat bubbles and the rigging animations. I am at a point in the chat bubble part of the video if I should just try to ask ChatGPT to come up with a script that applied the same functionality of creating the bubble, but to avail, there's too much of a knowledge curve for it to create code that is able to do the same job. I believe that providing a minimal understanding about how the code in your video works and how it's being applied would be incredibly useful for someone who has never watched your series (me). This video is beautiful and it's the first video that gives me serious advice about how to make interactable NPCs; It would be even better if you made it so that I don't have to have pause the video just to follow another video that could take me a couple hours to really master in my head.
What you just mentioned is exactly what game development is all about. You build systems on top of systems. No game is composed of just a single simple system. Learning how to put systems together is a necessary part of the learning process. But you don't need the chat bubble for the NPC interaction, the basic interaction logic does not depend on any other system.
Ya I agree, I get the whole 'this is game dev' but you are also making the other one in 2d and this one is called chat bubble 3d , is it the same thing?
@@paul7408 Yes, logic is usually completely independent of 2D or 3D, so yes with a few tweaks you can turn almost any 2D system/element into 3D and vice versa. unitycodemonkey.com/video.php?v=3zxTigjJr24
Minor optimization, but you could do your distance check and setting of the nearest interactable where you are adding to the list instead. Love the video, have a similar setup in the game I'm working on. public interface IInteractableObject { public string getLookAtText(NetworkIdentity onlooker); public void useObject(NetworkIdentity onlooker); public bool isInteractable(); }
I really like your No code Course in Unity, you could create new one with updates and maybe new genres if you have time in the future, I would 100% buy it!
Thank you very much for the great video! One question: what if I have some objects, that have different amount of actions (door - just open/close (1 action), but laptop - play, search, write email (3 actions)). How can I extend the existing logic to achieve this?
You could implement a function called GetInteractActions(); on the interface, that function would return a InteractAction[] where each InteractAction holds some kind of string actionName; and Action logicAction; Then modify the UI to get all the actions and show them to the player, depending on player input you run each of those actions.
I notice you're not hiding the interaction prompt - (E) Talk with Alice - when the key is pressed. I'm assuming that will be somewhat difficult since you're using Update() to keep it showing in the first place... but hiding it when the key is pressed would be the typical UI response you see in most every game. I love how you showed the refactor for using an Interface then... that was a great learning opportunity for those unfamiliar with them to see the resulting value.
Good point! That would depend on what you want the interaction to be like, just talk once or enable talking multiple times? Adding a simple timer to disable the game object visual/logic for half a second would be an easy way to give feedback to the player that the interaction was executed.
It tries to get the Component of that type attached to that game object. If it finds one it returns true, if not false. So in that case it tries to find a component of type NPCInteractable attached to any of the objects that the physics query hit. If it finds one then it calls the Interact(); function
Awesome! Please do a tutorial where character jumps over objects with animations(like small wall, ledge) and cover system like in GTA V. No other youtuber did a high quality tutorial on this matter
There is one "off topic question" I always have when watching Unity tutorial videos: Why no one uses Visual Studio with Unity? Always you have to add Usings manually or, when you want to create an element which is NOT a Monobehaviour, you have to create a script in Unity and rewrite everything by hand. Why not using VS and create simple classes or interfaces there?
I add the usings manually so that the tutorial is easy to follow, if I do it automatically with the keyboard shortcut then I would get tons of comments asking why a class does not exist because people would easily miss that and not know what they did wrong. Same thing for creating new files, it's easier to follow the tutorial if I do it the standard way although yes of course you could just create it directly in Visual Studio. So basically those two things are done solely for tutorial purposes, feel free to use shortcuts and never leave VS when working by yourself.
Cool theme for tutorial! Thank you again! Did you think, what would be if you need to pass more parameters to the IIneractable.Interact method, rather than the only Transform parameter? For example, if different types of interactables has it's own set of parameters, that they need in Ineract method? Generally seaking, you are already have DoorInteractable and ButtonInteractable, that needs a different set of parameters in Interact method - they both needs no parameters, but Transform is there.. a little bit confusing, because Door and Button become dependent of what they are don't need at all.
You can make an InteractParameters class and include that in the Interact(); function Then extend that class for specific interactions. So the DoorInteractable class has a DoorInteractParameters : InteractParameters And in the DoorInteractable.Interact(); you receive InteractParameters and cast it to DoorInteractParameters and then you have access to whatever parameters you want. That's exactly what I'm doing in the game that I'm currently working on that has lots of objects that need to be interacted with and some of them need extra parameters, like the crafting station needs to know which inventory to grab the items from. unitycodemonkey.com/video.php?v=kcsHQbzZaA4
You are right, I didn't watch this video yet. But if so, then you have to know what exactly intractable you are calling to create a certain type of parameter. And there will be a switch statement, or reflection, or chain of responsibility pattern, or something else.
@@antonorlov8838 You ask the object to get the ActionParams needed for that object. So every class that implements IInteractable also implements GetActionParams() and returns the specific type required to interact with that specific object.
@@CodeMonkeyUnity Can you explain a bit more about the last comment you 've made Code Monkey? Lets assume we are calling IInteractable.Interact(InteractParameters params) We still need to know about the object to pass some parameters inside Interactor. This has been an ultimate problem for me couldn't escape from switch cases. I would be really appreciated to know this more.
Hi. Good tutorial, but what if Chat bubble setting is problem with 3D object near by or moving (turning NPC)? It must be UI elements right ? but this completly destroy setup of bubble elements displacement
I covered the new input system in detail here unitycodemonkey.com/video.php?v=Yjee_e4fICc All the logic in this video would be exactly the same, just swap Input.GetKeyDown with the new input action
Both methods would work, only difference is this does not require a separate component/gameObject and the layerMask can be used for only hitting interactable objects.
Sorry I still don't understand how the interface mehthods work? I have watched your video on interfaces and I understand that. So how does it work like if you have 5 different food objects that you can pick up or place down? How does the interface code work?
What specifically don't you understand? The interface acts like a contract, when a class implements that interface it must implement those functions, so by writing code that works with that interface it will work with any class that implements that interface unitycodemonkey.com/video.php?v=MZOrGXk4XFI
Thank you so much, this will be super helpful for our project. Is it okay if we use parts of this code in our project, its for a school project? Have a wonderful day and thanks for everything you do for the community!
I love this video and have used the system / a few variations of many times. A question I had, how performant is this approach if we need multiple pverlap spheres for different cases? For example, we have IInteractable. How about we add another 4 or 5 interfaces, like ITargetable for enemies for example? Would this tank performance?
what is more performant: running something like Physics.OverlapSphere in update, or to have an instantiated, invisible, sphere gameobject checking collision?
I haven't done any tests but they should be pretty much the same. Although with manually calling OverlapSphere you can also limit how many times you run it if you have performance issues. If the player isn't moving insanely fast you can just test about 10 times per second instead of every single Update
Another great video! 😆👍 I'm really enjoying your tutorials... *BUT!* It would be really helpful if you could add some kind of Anotation overlay during editing, that labels which C# Script you're editing on screen... it's kind of hard to keep track of that while you're flipping back and fourth between the different ones. 💛👍
Nice video! I noticed that you always when you opened a new C# script delete the start and update method. Did you know that you are able to modify the Script Templates that Unity uses? So you can just edit these files and delete the two methods and every time you create a new C# script the new script won't have them. You just have to edit the file %EDITOR_PATH%\Data\Resources\ScriptTemplates\81-C# Script-NewBehaviourScript.cs.
Yeah I know that option exists but if I do that then it might confuse some people as to why when I do "create new C# script" the result is different from what they see. So because of that I just leave it as the default even though yeah I always delete it pretty much automatically.
thach good and all but how can we make similar system but to work with raycast instead off Physics sphere ? im try to make Interactable system for my game as well and i wand the object the player looks not only by distance. my game have a lot off Interactable objects and it's fps game i don't want the player to be able to pick up objects behind walls and pic different item for what it looks because it closer ect. it need to work on the interact button needs to be on the object the player looks and to not work if have other coltion in front of them.
It's the same idea, but instead of OverlapSphere you do a OverlapBox in front of the player. If you want to test for walls then yes use a BoxCast to find if the object is behind a wall or not
SphereCast involves movement where the "virtual Sphere" moves in some direction and tests for all the objects it hits. Whereas OverlapSphere simply tests for all objects within range of that position. Basically a OverlapSphere works the same as a SphereCast with 0 distance, so if you don't need movement just use OverlapSphere
I find 2 better methods for getting interactables - either a box collider placed in front of the player and chekcing for it's collision with an interractable OR placing a empty game object in front of the player and using that as the center of hte spehere/box check. That way you will allways get back only the interactables right in front of you, so there is no need to a distance check. That said, I cannot get the chat box to work, it's not facing the player and it's horribly oversized, so obviously it needs to be modified to work in 3D, as your tutorial is for a 2D one.
Thanks for the video CM! I've noticed that here you use OverlapSphere, but in other videos you've used a spherical Raycast. Which is better? Is there one that is more performant?
It depends if you want the virtual sphere to move or not. OverlapSphere tests on a single point, SphereCast "moves" that virtual sphere and tests all collisions along the way. If you use SphereCast with a distance of 0 then it behaves just like OverlapSphere, I believe both end up the same in terms of performance.
I'm implementing 3d gameplay with your other course, complete multiplayer one. It seems like there you used ray but here you used collider search. Which one would you suggest me to follow? (my game is basically an fps coop)
It all depends on what you're trying to do. Are you trying to find a specific exact point in the world? Use a raycast. Are you trying to find objects in an area? Use OverlapSphere
@@CodeMonkeyUnity got it that sounds cool, actually maybe I should make a modul for "trying to find" things in the world. like it can do its own logic depending on what itS looking for. But I'm not there yet :D I'm still not happy with my fps controller but I'll get there
I made a similar setup but with "InteractableItem" being a class derived from monobehaviour with "virtual void Interact()" method and other interactable item classes being inherited from the "InteractableItem" class. I don't know if that's the best approach or the difference bitween these two approaches.
The main limitation is C# classes can only extend a single base class. So for example if your NPCs had some kind of Person base class then you couldn't extend both Person and InteractableItem Whereas with interfaces you can implement as many as you want so it's a more flexible approach.
@@CodeMonkeyUnity Oh.. Understood... In my case there were no NPCs. Just objects you can interact with which triggers appropriate events. So what you saying is I can have my NPCs inherit from class "NPCclass" but it can also have inheritance from the interface "InteractableItem"..? did i get it right?
Well, We created IInteractable made an abstraction between. But still we have unnecessary Transform parameter inside Button & Door. What if we need 2 parameters inside an interactable, are we going to extend that Interact function inside IInteractable? How would you approach to that
Hey, How do you get the lerping to work every time? it lerps the animation on the first interaction, however, after that, the head snaps to the position, should i be setting the lookAtPosition to false after it looks at the player?
You mean the Animation Rigging? I don't remember if I handled the reset, basically if the Player is no longer in range you should Lerp the weight back to 0 so they go back to looking forward.
@@CodeMonkeyUnity Ahh okay, I think I understand. I'm gonna have to play around with it, because I noticed it happens in your video as well. It works on the first interaction, you can see the head moving smoothly, however, every interaction after that will snap the head to the players position.
Use a normal text on a normal canvas instead of a separate one. I made something like it when I made a mini RPG ruclips.net/video/PGRt-yjuiII/видео.html
6.30m- Please answer me. How to apply that chat bubble that you made in 2D and now use it for 3D? in order to be able to see the text in the game, I have to put that text in 3D on the canvas that is set in world-space. however the text does not change at all. I do not understand? And according to you, the word after each setting for you is - simple. And as I said in one of the previous comments, nothing is simple for me when watching your videos. you are totally complicating it. Can you please explain 2d chatbubble 3d chatbubble?
Hey Code Monkey, love the tutorials! Do you have a tutorial you made or a recommended tutorial for building a Dialogue System? More specifically, a fully functional Dialogue System for dialogue between characters, narrative story and what not.
Hmm the only thing on that topic that I've covered was a simple TextWriter unitycodemonkey.com/video.php?v=ZVh4nH8Mayg For that kind of system you could probably store all that data in scriptable objects unitycodemonkey.com/video.php?v=7jxS8HIny3Q
In your tutorial for the chat bubble you were in 2d. I'm confused with how i can use the tutorial in this 3d project. I'm a complete beginner to coding and unity.
The chat bubble is a flat element, so I just converted the canvas into a world canvas and swapped Vector2 for Vector3 unitycodemonkey.com/video.php?v=3zxTigjJr24
Collider2D[] colliderArray= Physics2D.OverlapCircleAll(transform.position, interactRange); when ı write this it says it can not convert to the UnityEngine.Collider2D to the UnityEngineCollider2D[]
That's odd, did you save your code? That looks correct, Physics2D.OverlapCircleAll does indeed return a Collider2D[] Just make sure it's not Physics2D.OverlapCircle which returns just one
I downloaded the project files but the scene isn't loading properly. It's just a plane with a nonfunctional player controller. I made sure to get all of the addons. Maybe i imported it improperly?
Interfaces are cool, but you are still pasting the same code for interface methods to every class that implements it. If some method has to be changed, you need to paste the code again. What would be the way around this?
They say the find command is tiring for the computer, so I avoided using the find command, I was just thinking of using it in the start function when the game starts, but I wasn't sure.
How could we do that with two-sided? For example, we have different interactable objects & but our character will react differently for every object he interacts. Should i pass Interactor inside Interact method in Interactable, and reach the methods like; OnInteractPolice(); inside Interactor? This means we have to create all the methods for every interaction we do right? How would approach to that problem; We interact different objects, our character reacts different every object it interacts.
Hi I'm in the NPC Interact part of the lecture and I ended up getting the error: error CS0246: The type or namespace name 'NPCInteractable' could not be found (are you missing a using directive or an assembly reference?) this is my code: using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerInteract : MonoBehaviour { private void Update() { if (Input.GetKeyDown(KeyCode.E)) { float interactRange = 2f; Collider[] colliderArray = Physics.OverlapSphere(transform.position, interactRange); foreach (Collider collider in colliderArray) { if (collider.TryGetComponent(out NPCInteractable npcInteractable)) { npcInteractable.Interact(); } } } } }
I'm using a raycast in my game to detect interactive objects etc in my game (from the player camera to the interactive object). I love you approach to interact with objects, but which one do you reckon is more optimized?
It depends if you want to interact with the object only when looking at it or based on proximity, I used that method in the Pick Up Items system unitycodemonkey.com/video.php?v=_aC3NVIQ-ok
Hey Man, Lovin the tutorial so far, have learnt alot about different function in code. However ive ran into a small issue, i cannot get any console output of displaying the colliders in a scene and getting the "Interact!" message to appear in the console. ive been following this tutorial for buttons do u possibly know why?
Maybe you didn't add a collider to the objects, maybe they're not on the right layer, maybe you didn't assign the layer in the layer mask, maybe your raycast isn't using the correct parameters. Check each of those individually. Alternatively download the project files and compare with your own
Create an Animator controller, create an Animation where the door opens, another where the door closes. Then add a Bool parameter IsOpen, when that parameter is true play the open animation, when false play the close animation. Then just control that parameter through code
If you use the Unity Ad network then Unity will pay you. You can view the stats in your Unity dashboard. But if you use Unity Mediation coupled with AdMob then I'm not entirely sure what happens in that scenario.
Amazing tutorial! I have a question... What is there any difference between an abstract class and Interfaces? If I use inheritance instead of Interface, would it make an actual difference or would it be the same?
Good evening, we could create an abstract class with a virtual Interact() method, overloaded in the different child classes. The difficulty is to find a parent class that has as children a door, a button, characters, and potentially lots of objects. The interface avoids this problem.
@@jean-michel.houbre Another limitation related to the language: a given class can inherit only from one class at a time (abstract or not), but you can implement as many interfaces as you want.
Yeah, as they said, you implement all the interfaces, but just one base class. On the other hand, interfaces cannot be serialised. You won't be able to have a serialised list of IInteractiables or something else in the editor. That's sad. Sometimes you'd like to be able. And then you start using Odin serialiser and turn to that dark side. )))
You can only inherit from a single base class whereas you can implement as many interfaces as you want. So if your NPC had a base Person class you could not inherit from both Person and Interactable
Greetings Code Monkey Unity, I would like to ask a question regarding to the relation between ruclips.net/video/MIt0PJHMN5Y/видео.html (Simple Key Door System in Unity) and this video. If i want to implement the Interface code from this video into (Simple Key Door System in Unity) from [3.04 - 10.02] to obtain the key via the code line (Input.GetKeyButton), which code should i put into? According to the problem i'm facing right now, the code that i make has no error and i can interact with any object. When my character stands near the key, the UI can show the press button and the text, but when i want to interact with the key, the key can't react with the button i press... It would be grateful if you are willingly to answer my question, thanks!
Obtain the key how? By approaching and pressing the interact button? You would make some key object with some script that has IInteractable, just with that the player will be able to interact with it so then on the interact code you add the Key to the player's KeyHolder.
Between key down and running that interaction, run a coroutine that will wait for key up an and measure time it took, if enough then run interaction, else cancel.
That would be the same logic as here in order to identify when objects are in range, but then instead of calling the function on a KeyDown you would maybe increase some float timer while the key was held down and trigger the interaction after it goes above a threshold. Or look into the new Input System and look at the Hold interactor which will trigger the performed event only after that hold time has elapsed unitycodemonkey.com/video.php?v=Yjee_e4fICc
It depends on what you mean by NPC. What do you want it to do? It could be as simple as a game object with a character standing Idle, or something complex like a Companion that follows you and fights. Both are NPCs so it really depends specifically what you are trying to do.
Thank you so much for the tutorial! It helped me a lot. Maybe someone here can tell me how to make the player also turn his head towards the NPC? I would be very grateful
You set up the IK to follow a transform, then through code you position that target transform wherever you want, like what I did here ruclips.net/video/UL2EbxqwozM/видео.html
Code monkey I appreciate your work please and please their lots of videos on making multiplayer lobby, in game inventory and shop system. But if you try to search for shop system for multiplayer in start menu there's non like I don't want to make RPG I just wanna make a game where my players are able to buy characters (cars) and enter game with that character (car) but I don't how to please make a tutorial about it I'm making a multiplayer car race game I want players to buy cars and equip it then enter game with it, please (using netcode or photon)
@@ewwitsantonio Reduces the complexity of the design, and it is not the Player who should know which NPCs it communicated with; it is the NPCs who should know they need to communicate with the Player.
Doesn't make sense for the NPC to test the distance since it is the Player who is attempting to initiate the interaction, that would only make sense if the NPC was running towards the player to initiate some conversation or give them a quest. And like I mentioned in the video doing a distance check would be wasteful so that's why I prefer using a simple Physics query.
@@CodeMonkeyUnity Proximity gets tested on collisions. Both objects get tagged. The game shows the conversation via a scriptable object driver conversation using both tags. This is an Object-Oriented Design. For simplicity, you could smush the logic into the scriptable object; however, this would be less Object-Oriented than the other.
@@CodeMonkeyUnity Physics query is only faster because the physics system probably has some kind of chunk-based batching built in. It's quite trivial to implement and would most likely make distance checking faster.
✅ Get the Project files unitycodemonkey.com/video.php?v=LdoImzaY6M4
🌍 Get my Complete Courses! ✅ unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
👇 Click on Show More
🎮 Get my Steam Games unitycodemonkey.com/gamebundle
POLYGON - City Pack cmonkey.co/synty_city_talknpcs
POLYGON - Heist Pack cmonkey.co/synty_heist_talknpcs
Basic Motions Animations assetstore.unity.com/packages/3d/animations/basic-motions-157744?aid=1101l96nj&pubref=talktonpcs
🔴 RELATED VIDEOS 🔴
Why you should NOT make everything PUBLIC! ruclips.net/video/pD27YuJG3L8/видео.html
Simple Chat Bubble in Unity! (Chat, NPC, Multiplayer) ruclips.net/video/K13WnNL1OYM/видео.html
Kickstart your game with First and Third Person Controllers! (FREE Unity Starter Assets) ruclips.net/video/jXz5b_9z0Bc/видео.html
Make your Animations DYNAMIC with Animation Rigging! ruclips.net/video/LEwYmFT3xDk/видео.html
SMOOTH with LERP! (Move, Rotate, Float) ruclips.net/video/jAN2IoWdPzM/видео.html
What are Interfaces? (C# Basics) ruclips.net/video/MZOrGXk4XFI/видео.html
Can i use your Project file in my project for commercial purposes
Can u do the same tuto but using raycast
Its because its better when using raycast i hope u see this comment and do tuto pls
PLEASE ANSWER ME ! why do I keep getting this error message in the console -ArgumentException: The Object you want to instantiate is null.
UnityEngine.Object.Instantiate[T] (T original) (at :0)
GamePrefabAssets.get_i () (at Assets/Asset_Game/Test_Stuff/ChatBubble/GamePrefabAssets.cs:16)
ChatBubble.Create (UnityEngine.Transform parent, UnityEngine.Vector3 localPosition, ChatBubble+IconType iconType, System.String text) (at Assets/Asset_Game/Test_Stuff/ChatBubble/ChatBubble.cs:15)
NPCInteract.Interact () (at Assets/NPCInteract.cs:13)
PlayerInteract.Update () (at Assets/PlayerInteract.cs:24)
- I did everything like you 5 times, I went through all the video clips that are needed for this, created chat bubbles. However, I keep getting this message, why?
I am a student software engineer which is doing a game dev course, thank you for this amazing tutorial!
Btw I loved Blueprint Tycoon, played it a lot!
sprinkling getkeydown all over the creation is precisely the kind of 💩 that makes this the worst way to “teach” people unity…. 🤦♂️
15:55 Optimization tip for the distance checking part:
- Vector3.Distance involves a square root in the math, which is super slow to compute. Since you're only checking which object is the closest, you can use squared distances to remove the square root and make the check faster.
- There's no Vector3.SquaredDistance static method, however you can use (pos1 - pos2).sqrMagnitude. This returns the squared distance between pos1 and pos2.
I learned the hard way about this performance tip ages ago, the workaround you posted sounds neat and I'll make sure to give this a try soon. Much obliged.
That was true many years ago, but now there is no real measurable difference in using Vector3.Distance compared to sqrMagnitude. See Tarodev's channel and his video "Unity Code Optimization - Do You Know Them All?"
@@slygamer01 I just checked that passage. Interesting...!
@@slygamer01 I read something similar when I was looking through this yesterday, as I figured the best way to optimize Distance would be to settle for the Q3 Fast Inverse Square Root function. What I found was a few measurements showing that the difference was negligible, as well as the usual smug nonsense of a Unity forum war. It proved to be rather amusing up until it wasn't.
I was having performance issues but this fixed my problem thanks a lot
I really must be getting better at this coding thing because the whole video I was like, "This code is neither nice or clean, why isn't he using an interface!" You got me good CM! Cheers!
Oh man, I was stumbling my way through basically this very thing, but started with object interaction and was going to use it as the base for my NPC conversations. But then you come along and show off the right way to do it. Thanks! Now I get to go fix everything I did wrong.
for YEARS i've struggle to understand Interfaces. two senior devs tried teaching me for days, ive looked to yt videos and never got it quite right. until this video and your simple and amazing explanation. thanls SO MUCH for this!
Fantastic teaching. I've watched enough of your videos to anticipate we'd get to interfaces, but buildup (showing the scaling issues and the solution) is a fantastic teaching method.
Thanks! I'm glad you liked the video!
Exactly when I am stuck on a point, code monkey comes from heaven to save me. Thank you so much CM!!
lol, same
Conspiracy: Code Monkey is an angel of knowledge, set to test humanity's willingness to pursue knowledge. Part of a way he tests is to remove the "I don't know what to do next" excuse by always providing ways as the needs arise.
At 24:46, instead of checking proximity to NPCs and taking the closest, this has a potential problem where you are standing between the two, closer to Alice, but are facing Bob and want to talk to Bob. In this case it will still give you the wrong interaction. I personally would calculate the angle-difference between player-forward vector and vector from player to NPC, and take the one with the smallest angle difference. (i.e. calculating in code, the answer to the question "which one am I facing?")
Yup that's a good point, adding player direction into the logic would indeed make it feel more natural
@@CodeMonkeyUnity Nice video though, I should have mentioned! 😃
Excellent video! Covered some great topics, demonstrated them in a clear and thorough manner, and the visuals and initial setup of the project are beyond the normal tutorial grade. Great work :)
I actually encountered this problem many times in the past. What I think is a good solution is making an npc component which inherits an interactable interface. Your solution is great too and I really enjoyed the video. Keep it up
Plus it also supports every interactable object with only one line of code
After a long time I came to see video I was busy . I was studying web development. Again awesome video .
I don't know how you do it, but as soon as I need something, you immediately release a video on this topic, thank you!
I had ideas on how this would be done but this will be a great skill to have for multiple uses. thanks for this
At the beginning of the video, I immediately thought about interfaces and was surprised that you ignored them... but in the end you corrected yourself... And by the way, your explanation of interfaces for beginners is impeccable )
your voice and the way u talk makes me smile.
I got really scared after seeing the solution without an interface, thinking that this would be your final proposal :) great tutorial!
Quality of your video has improved a lot since I last visited sometime ago. Keep it up:)
Thanks! I'm always trying to improve!
Great tutorial ... very clear, neat and detailed at the same time.
Loving the vids and how you break down the logic for further additions and improvements. I'd be keen to see you possibly do a tutorial on an Anno style system with automated NPC pathfinding to new buildings / task finding etc - Unless you have something similar already
For recalculating path you would probably just have the Pathfinding system fire off an event when the pathfinding map changes (like when a new building/road is placed) then have the unit listen to that event and request a new path.
I made a nice Task System a long time ago which I used in my game Battle Royale Tycoon unitycodemonkey.com/video.php?v=rQXr9XTu6CI
You are an excellent teacher. Thanks!
Dude your tutoriales are VERY good and informative. My only problem now is deciding which of the like 7 ideas I have for games I should start making into a complete one lol
That is always a tricky problem! I myself also have hundreds of ideas for games/videos but not enough time to do them all at once!
I found myself in a similar situation earlier. For me I decided to make the easiest of them first. So I can finish it move on to the next.But in my case the second and maybe even the third idea is like an extension of the first so i can reuse and repurpose a lot of it. you could say they happen in the same universe or whaterver. If i will finish any of it is yet to be decided.. lol.
You could also approach it in way like "which game benefits you the most?"
Nice and clean, nothing to report!
Hey Codemonkey. So this was one of the hardest problems I've ever had to figure out and I succeeded without the physics.overlap function. I did run into it during research but failed to see how I could effectively use it. I see now how useful it would have been in my situation, I might still go back and swap my method for yours if it becomes too unweildy. I ended up adding an interact script to every interactable item which then each tracks the distance from itself to the player so it knows when to pop up the UI banner. I will definitely use this video as reference, there is hardly anything out there on this subject, thank you.
That approach is less efficient but depending on how many Interactable objects you have it might not necessarily be a problem. If you come across performance issues in the future then that could be an easy way to get a few more fps
Best video I've seen in about NPCs on RUclips by far, however as a very new game developer (if you can call me that), I feel you should have made the video tutorial without referencing code from another video. The chat bubble concept as well as the rigging concept are wonderful and amazing, however if the goal is to be easy to follow, the tutorial should 100% be independent of other skills other than the ones showed in the video. I quite frankly feel really discouraged to continue with this tutorial because it requires me to learn and apply two more unity tutorials, which are the skills and knowledge revolving around the chat bubbles and the rigging animations.
I am at a point in the chat bubble part of the video if I should just try to ask ChatGPT to come up with a script that applied the same functionality of creating the bubble, but to avail, there's too much of a knowledge curve for it to create code that is able to do the same job. I believe that providing a minimal understanding about how the code in your video works and how it's being applied would be incredibly useful for someone who has never watched your series (me). This video is beautiful and it's the first video that gives me serious advice about how to make interactable NPCs; It would be even better if you made it so that I don't have to have pause the video just to follow another video that could take me a couple hours to really master in my head.
What you just mentioned is exactly what game development is all about. You build systems on top of systems. No game is composed of just a single simple system.
Learning how to put systems together is a necessary part of the learning process.
But you don't need the chat bubble for the NPC interaction, the basic interaction logic does not depend on any other system.
Ya I agree, I get the whole 'this is game dev' but you are also making the other one in 2d and this one is called chat bubble 3d , is it the same thing?
@@paul7408 Yes, logic is usually completely independent of 2D or 3D, so yes with a few tweaks you can turn almost any 2D system/element into 3D and vice versa. unitycodemonkey.com/video.php?v=3zxTigjJr24
Minor optimization, but you could do your distance check and setting of the nearest interactable where you are adding to the list instead. Love the video, have a similar setup in the game I'm working on.
public interface IInteractableObject
{
public string getLookAtText(NetworkIdentity onlooker);
public void useObject(NetworkIdentity onlooker);
public bool isInteractable();
}
I always find your tutorials useful and helpful. and as usual clean expandable code.
I'm glad the videos have helped you! Thanks!
Why did you use Physics.CheckSphere and not a collider trigger? Are there any disadvantages?
Mainly just personal preference, adding a trigger collider on top of the player game object would indeed also work.
Finally, this is what all i need.
Thank you
ahem......... **GENERAL KENOBI**
awesome tutorial as always 👍👍👍
I'm glad it helped you! Thanks!
I really like your No code Course in Unity, you could create new one with updates and maybe new genres if you have time in the future, I would 100% buy it!
Thank you very much for the great video!
One question: what if I have some objects, that have different amount of actions (door - just open/close (1 action), but laptop - play, search, write email (3 actions)). How can I extend the existing logic to achieve this?
You could implement a function called GetInteractActions(); on the interface, that function would return a InteractAction[] where each InteractAction holds some kind of string actionName; and Action logicAction;
Then modify the UI to get all the actions and show them to the player, depending on player input you run each of those actions.
I notice you're not hiding the interaction prompt - (E) Talk with Alice - when the key is pressed. I'm assuming that will be somewhat difficult since you're using Update() to keep it showing in the first place... but hiding it when the key is pressed would be the typical UI response you see in most every game.
I love how you showed the refactor for using an Interface then... that was a great learning opportunity for those unfamiliar with them to see the resulting value.
Good point! That would depend on what you want the interaction to be like, just talk once or enable talking multiple times? Adding a simple timer to disable the game object visual/logic for half a second would be an easy way to give feedback to the player that the interaction was executed.
I don't understand this part 12:19, I mean why are we connecting NPCInteractable? And can you explain TryGetComponent more?
It tries to get the Component of that type attached to that game object. If it finds one it returns true, if not false.
So in that case it tries to find a component of type NPCInteractable attached to any of the objects that the physics query hit. If it finds one then it calls the Interact(); function
24:06 not all difference. Vector3.Distance dnt work in 2D
This is very helpful!
This tutorial is awesome !!!!!🤘🤘🤘
Awesome! Please do a tutorial where character jumps over objects with animations(like small wall, ledge) and cover system like in GTA V. No other youtuber did a high quality tutorial on this matter
How did it go? Made flappy bird HD yet?
There is one "off topic question" I always have when watching Unity tutorial videos: Why no one uses Visual Studio with Unity? Always you have to add Usings manually or, when you want to create an element which is NOT a Monobehaviour, you have to create a script in Unity and rewrite everything by hand. Why not using VS and create simple classes or interfaces there?
I add the usings manually so that the tutorial is easy to follow, if I do it automatically with the keyboard shortcut then I would get tons of comments asking why a class does not exist because people would easily miss that and not know what they did wrong.
Same thing for creating new files, it's easier to follow the tutorial if I do it the standard way although yes of course you could just create it directly in Visual Studio.
So basically those two things are done solely for tutorial purposes, feel free to use shortcuts and never leave VS when working by yourself.
@@CodeMonkeyUnity got ya! Thanks :)
Cool theme for tutorial! Thank you again!
Did you think, what would be if you need to pass more parameters to the IIneractable.Interact method, rather than the only Transform parameter? For example, if different types of interactables has it's own set of parameters, that they need in Ineract method? Generally seaking, you are already have DoorInteractable and ButtonInteractable, that needs a different set of parameters in Interact method - they both needs no parameters, but Transform is there.. a little bit confusing, because Door and Button become dependent of what they are don't need at all.
You can make an InteractParameters class and include that in the Interact(); function
Then extend that class for specific interactions.
So the DoorInteractable class has a DoorInteractParameters : InteractParameters
And in the DoorInteractable.Interact(); you receive InteractParameters and cast it to DoorInteractParameters and then you have access to whatever parameters you want.
That's exactly what I'm doing in the game that I'm currently working on that has lots of objects that need to be interacted with and some of them need extra parameters, like the crafting station needs to know which inventory to grab the items from. unitycodemonkey.com/video.php?v=kcsHQbzZaA4
You are right, I didn't watch this video yet. But if so, then you have to know what exactly intractable you are calling to create a certain type of parameter. And there will be a switch statement, or reflection, or chain of responsibility pattern, or something else.
@@antonorlov8838 You ask the object to get the ActionParams needed for that object. So every class that implements IInteractable also implements GetActionParams() and returns the specific type required to interact with that specific object.
@@CodeMonkeyUnity Can you explain a bit more about the last comment you 've made Code Monkey? Lets assume we are calling IInteractable.Interact(InteractParameters params)
We still need to know about the object to pass some parameters inside Interactor. This has been an ultimate problem for me couldn't escape from switch cases. I would be really appreciated to know this more.
Hi. Good tutorial, but what if Chat bubble setting is problem with 3D object near by or moving (turning NPC)? It must be UI elements right ? but this completly destroy setup of bubble elements displacement
Shader did the job. One day stuck, but now I got working shader cancontinue in watching
A great motivator to make a code to open the door when there is such a lot of money behind it )))
Any chance we could get a tutorial for this using the new input system??
I covered the new input system in detail here unitycodemonkey.com/video.php?v=Yjee_e4fICc
All the logic in this video would be exactly the same, just swap Input.GetKeyDown with the new input action
@@CodeMonkeyUnity Thanks
still can't seem to figure out how to use this with a button in the new input system im on mobile not pc
Is there a reason to use physics overlap instead of attaching a trigger to the player?
Both methods would work, only difference is this does not require a separate component/gameObject and the layerMask can be used for only hitting interactable objects.
Sorry I still don't understand how the interface mehthods work? I have watched your video on interfaces and I understand that. So how does it work like if you have 5 different food objects that you can pick up or place down? How does the interface code work?
What specifically don't you understand? The interface acts like a contract, when a class implements that interface it must implement those functions, so by writing code that works with that interface it will work with any class that implements that interface unitycodemonkey.com/video.php?v=MZOrGXk4XFI
Thank you so much, this will be super helpful for our project. Is it okay if we use parts of this code in our project, its for a school project?
Have a wonderful day and thanks for everything you do for the community!
Yup feel free to use any of the code in the videos/utilities in your own projects, free or commercial.
Thanks!
I love this video and have used the system / a few variations of many times.
A question I had, how performant is this approach if we need multiple pverlap spheres for different cases? For example, we have IInteractable. How about we add another 4 or 5 interfaces, like ITargetable for enemies for example? Would this tank performance?
what is more performant: running something like Physics.OverlapSphere in update, or to have an instantiated, invisible, sphere gameobject checking collision?
I haven't done any tests but they should be pretty much the same. Although with manually calling OverlapSphere you can also limit how many times you run it if you have performance issues. If the player isn't moving insanely fast you can just test about 10 times per second instead of every single Update
Another great video! 😆👍 I'm really enjoying your tutorials...
*BUT!*
It would be really helpful if you could add some kind of Anotation overlay during editing, that labels which C# Script you're editing on screen... it's kind of hard to keep track of that while you're flipping back and fourth between the different ones. 💛👍
I do leave the top bar visible with the file list so you can see that and I try to mention it with voice but yea sometimes I forget
Nice video!
I noticed that you always when you opened a new C# script delete the start and update method. Did you know that you are able to modify the Script Templates that Unity uses? So you can just edit these files and delete the two methods and every time you create a new C# script the new script won't have them. You just have to edit the file %EDITOR_PATH%\Data\Resources\ScriptTemplates\81-C# Script-NewBehaviourScript.cs.
This to should be under every video. Newbies won't do this. But they will get used to removing junk from scripts.
Yeah I know that option exists but if I do that then it might confuse some people as to why when I do "create new C# script" the result is different from what they see.
So because of that I just leave it as the default even though yeah I always delete it pretty much automatically.
thach good and all but how can we make similar system but to work with raycast instead off Physics sphere ?
im try to make Interactable system for my game as well and i wand the object the player looks not only by distance.
my game have a lot off Interactable objects and it's fps game i don't want the player to be able to pick up objects behind walls and pic different item for what it looks because it closer ect.
it need to work on the interact button needs to be on the object the player looks and to not work if have other coltion in front of them.
It's the same idea, but instead of OverlapSphere you do a OverlapBox in front of the player. If you want to test for walls then yes use a BoxCast to find if the object is behind a wall or not
I love your videos 💞
Hey! I expected using a ray- or spherecast instead of physics overlap. Can you explain why you use one over another?
SphereCast involves movement where the "virtual Sphere" moves in some direction and tests for all the objects it hits.
Whereas OverlapSphere simply tests for all objects within range of that position.
Basically a OverlapSphere works the same as a SphereCast with 0 distance, so if you don't need movement just use OverlapSphere
Im stuck on the Chat bubble part. im not sure how do like make the text that pops up without having the same prefab as urs
I covered that in detail in this tutorial ruclips.net/video/K13WnNL1OYM/видео.html
@@CodeMonkeyUnity Tysm bro ur great u have the time to reply and make videos is great much respect🙌
I find 2 better methods for getting interactables - either a box collider placed in front of the player and chekcing for it's collision with an interractable OR placing a empty game object in front of the player and using that as the center of hte spehere/box check. That way you will allways get back only the interactables right in front of you, so there is no need to a distance check.
That said, I cannot get the chat box to work, it's not facing the player and it's horribly oversized, so obviously it needs to be modified to work in 3D, as your tutorial is for a 2D one.
You are a saint sir!❤
Thanks for the video CM! I've noticed that here you use OverlapSphere, but in other videos you've used a spherical Raycast. Which is better? Is there one that is more performant?
It depends if you want the virtual sphere to move or not. OverlapSphere tests on a single point, SphereCast "moves" that virtual sphere and tests all collisions along the way.
If you use SphereCast with a distance of 0 then it behaves just like OverlapSphere, I believe both end up the same in terms of performance.
How did you implement blurry effect?? Like npc were blurry until you approached closed to them??
That's Depth of Field Post Processing
@@CodeMonkeyUnity thanks for the reply sir..... Got it, made that effect 😁
I'm implementing 3d gameplay with your other course, complete multiplayer one. It seems like there you used ray but here you used collider search. Which one would you suggest me to follow? (my game is basically an fps coop)
It all depends on what you're trying to do. Are you trying to find a specific exact point in the world? Use a raycast. Are you trying to find objects in an area? Use OverlapSphere
@@CodeMonkeyUnity got it that sounds cool, actually maybe I should make a modul for "trying to find" things in the world. like it can do its own logic depending on what itS looking for. But I'm not there yet :D I'm still not happy with my fps controller but I'll get there
I made a similar setup but with "InteractableItem" being a class derived from monobehaviour with "virtual void Interact()" method and other interactable item classes being inherited from the "InteractableItem" class.
I don't know if that's the best approach or the difference bitween these two approaches.
The main limitation is C# classes can only extend a single base class. So for example if your NPCs had some kind of Person base class then you couldn't extend both Person and InteractableItem
Whereas with interfaces you can implement as many as you want so it's a more flexible approach.
@@CodeMonkeyUnity Oh.. Understood... In my case there were no NPCs. Just objects you can interact with which triggers appropriate events.
So what you saying is I can have my NPCs inherit from class "NPCclass" but it can also have inheritance from the interface "InteractableItem"..? did i get it right?
Well, We created IInteractable made an abstraction between. But still we have unnecessary Transform parameter inside Button & Door. What if we need 2 parameters inside an interactable, are we going to extend that Interact function inside IInteractable? How would you approach to that
Hey, How do you get the lerping to work every time? it lerps the animation on the first interaction, however, after that, the head snaps to the position, should i be setting the lookAtPosition to false after it looks at the player?
You mean the Animation Rigging? I don't remember if I handled the reset, basically if the Player is no longer in range you should Lerp the weight back to 0 so they go back to looking forward.
@@CodeMonkeyUnity Ahh okay, I think I understand. I'm gonna have to play around with it, because I noticed it happens in your video as well. It works on the first interaction, you can see the head moving smoothly, however, every interaction after that will snap the head to the players position.
how can i make in first person the dialogue, not into world space but in hud?
Use a normal text on a normal canvas instead of a separate one. I made something like it when I made a mini RPG ruclips.net/video/PGRt-yjuiII/видео.html
Greetings, Code Monkey. I have a question, is the ChatBubble3D needs to be imported to the project as it was made in your previous video?
I changed some things to make it work in 3D, mainly I just added a 3D cube behind it so it didn't cause issues with the Depth of Field effect.
6.30m- Please answer me. How to apply that chat bubble that you made in 2D and now use it for 3D? in order to be able to see the text in the game, I have to put that text in 3D on the canvas that is set in world-space. however the text does not change at all. I do not understand? And according to you, the word after each setting for you is - simple. And as I said in one of the previous comments, nothing is simple for me when watching your videos. you are totally complicating it. Can you please explain 2d chatbubble 3d chatbubble?
Do I need to buy the asset packs to follow along, or can I just use my own assets and animations?
You can use this interaction system with whatever assets you want, it's not limited to any specific assets or any specific camera (2D,3D)
@@CodeMonkeyUnity Thank you.
This really helped!!!
Excelent video, but if i want to operate a cannon or control a seering wheel of a ship how do i dot it with interactions in an fps game?
When you trigger the interaction you would open up come kind of complex UI that contains buttons/sliders for all those actions
Hey Code Monkey, love the tutorials! Do you have a tutorial you made or a recommended tutorial for building a Dialogue System? More specifically, a fully functional Dialogue System for dialogue between characters, narrative story and what not.
Hmm the only thing on that topic that I've covered was a simple TextWriter unitycodemonkey.com/video.php?v=ZVh4nH8Mayg
For that kind of system you could probably store all that data in scriptable objects unitycodemonkey.com/video.php?v=7jxS8HIny3Q
In your tutorial for the chat bubble you were in 2d. I'm confused with how i can use the tutorial in this 3d project. I'm a complete beginner to coding and unity.
The chat bubble is a flat element, so I just converted the canvas into a world canvas and swapped Vector2 for Vector3 unitycodemonkey.com/video.php?v=3zxTigjJr24
@@CodeMonkeyUnity Thank you!
Collider2D[] colliderArray= Physics2D.OverlapCircleAll(transform.position, interactRange); when ı write this it says it can not convert to the UnityEngine.Collider2D to the UnityEngineCollider2D[]
That's odd, did you save your code? That looks correct, Physics2D.OverlapCircleAll does indeed return a Collider2D[]
Just make sure it's not Physics2D.OverlapCircle which returns just one
I downloaded the project files but the scene isn't loading properly. It's just a plane with a nonfunctional player controller. I made sure to get all of the addons. Maybe i imported it improperly?
You can't rotate the player with the mouse? You can't move? Is the game running? Got any errors in the console?
Interfaces are cool, but you are still pasting the same code for interface methods to every class that implements it. If some method has to be changed, you need to paste the code again. What would be the way around this?
Interfaces support a default implementation, you can implement the common parts in the interface itself and override when needed
@@CodeMonkeyUnity Thank you for your answers.
I want to get an opinion on a topic. Should I use serializefield or find method to access multiple gameobjects?
Depends on the context but if you want to run a specific function then make a SerializeField of that type and run the function directly on it.
They say the find command is tiring for the computer, so I avoided using the find command, I was just thinking of using it in the start function when the game starts, but I wasn't sure.
How could we do that with two-sided? For example, we have different interactable objects & but our character will react differently for every object he interacts. Should i pass Interactor inside Interact method in Interactable, and reach the methods like; OnInteractPolice(); inside Interactor?
This means we have to create all the methods for every interaction we do right? How would approach to that problem; We interact different objects, our character reacts different every object it interacts.
Hi I'm in the NPC Interact part of the lecture and I ended up getting the error:
error CS0246: The type or namespace name 'NPCInteractable' could not be found (are you missing a using directive or an assembly reference?)
this is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInteract : MonoBehaviour
{
private void Update()
{ if (Input.GetKeyDown(KeyCode.E))
{
float interactRange = 2f;
Collider[] colliderArray = Physics.OverlapSphere(transform.position, interactRange);
foreach (Collider collider in colliderArray)
{
if (collider.TryGetComponent(out NPCInteractable npcInteractable))
{
npcInteractable.Interact();
}
}
}
}
}
Sounds like you didn't make an NPCInteractable script, did you name it something difference?
@@CodeMonkeyUnity OHHH I gets, the script name didn't update to NPCInteractables and was just left as NpcInteractables, thank you so much lol!
I'm using a raycast in my game to detect interactive objects etc in my game (from the player camera to the interactive object). I love you approach to interact with objects, but which one do you reckon is more optimized?
It depends if you want to interact with the object only when looking at it or based on proximity, I used that method in the Pick Up Items system unitycodemonkey.com/video.php?v=_aC3NVIQ-ok
Hey Man, Lovin the tutorial so far, have learnt alot about different function in code. However ive ran into a small issue, i cannot get any console output of displaying the colliders in a scene and getting the "Interact!" message to appear in the console. ive been following this tutorial for buttons do u possibly know why?
Maybe you didn't add a collider to the objects, maybe they're not on the right layer, maybe you didn't assign the layer in the layer mask, maybe your raycast isn't using the correct parameters. Check each of those individually.
Alternatively download the project files and compare with your own
for me it says NPCInteractable could not be found am i missing something? cause im pretty sure i followed the tutorial correctly
Maybe you wrote a typo in the class name? It was created at 5:08
Better to add a check for the camera frustum, just to eliminate the cases when objects are behind.
Good tip! Could be done like I did the Backstab mechanic unitycodemonkey.com/video.php?v=78J493qWfDI
how do you do the door open? is there an animator or something and what do i name it? pls help me
Yup just a basic animator moving an object
@@CodeMonkeyUnity How do i do that then
@@CodeMonkeyUnity um What do i do?
Create an Animator controller, create an Animation where the door opens, another where the door closes. Then add a Bool parameter IsOpen, when that parameter is true play the open animation, when false play the close animation. Then just control that parameter through code
Hi, just a quick question. If I use unity ads and put my game on the Google store, who pays me? Google or unity?
Google I think so.
@@kunj1064 oh I hope not, I've got a hold on payments that I don't know how to fix cos it's not telling why. And I can't find a number to sort it.
Ooo
If you use the Unity Ad network then Unity will pay you. You can view the stats in your Unity dashboard.
But if you use Unity Mediation coupled with AdMob then I'm not entirely sure what happens in that scenario.
@@CodeMonkeyUnity ok
I made new project on 3d but when i put package it's all pink :(
You just need to install the Universal RP package and set the project to use it
@@CodeMonkeyUnity Thanks i'll try at the morning
thanks. i am going to use this for a map selector hub world. it should also work with raycasts i think
Edit: it did👍
Yup you could indeed just do a raycast towards the center of the screen
Thank you!!
Amazing tutorial! I have a question... What is there any difference between an abstract class and Interfaces? If I use inheritance instead of Interface, would it make an actual difference or would it be the same?
Good evening,
we could create an abstract class with a virtual Interact() method, overloaded in the different child classes.
The difficulty is to find a parent class that has as children a door, a button, characters, and potentially lots of objects.
The interface avoids this problem.
@@jean-michel.houbre Another limitation related to the language: a given class can inherit only from one class at a time (abstract or not), but you can implement as many interfaces as you want.
Yeah, as they said, you implement all the interfaces, but just one base class. On the other hand, interfaces cannot be serialised. You won't be able to have a serialised list of IInteractiables or something else in the editor. That's sad. Sometimes you'd like to be able. And then you start using Odin serialiser and turn to that dark side. )))
You can only inherit from a single base class whereas you can implement as many interfaces as you want.
So if your NPC had a base Person class you could not inherit from both Person and Interactable
Greetings Code Monkey Unity, I would like to ask a question regarding to the relation between ruclips.net/video/MIt0PJHMN5Y/видео.html (Simple Key Door System in Unity) and this video. If i want to implement the Interface code from this video into (Simple Key Door System in Unity) from [3.04 - 10.02] to obtain the key via the code line (Input.GetKeyButton), which code should i put into?
According to the problem i'm facing right now, the code that i make has no error and i can interact with any object. When my character stands near the key, the UI can show the press button and the text, but when i want to interact with the key, the key can't react with the button i press...
It would be grateful if you are willingly to answer my question, thanks!
Obtain the key how? By approaching and pressing the interact button? You would make some key object with some script that has IInteractable, just with that the player will be able to interact with it so then on the interact code you add the Key to the player's KeyHolder.
@@CodeMonkeyUnity Yes! By approaching it and interact with it by pressing the interact button
Can you make tutorial how to made interaction system where you need to hold e (not press) some time to interact
Between key down and running that interaction, run a coroutine that will wait for key up an and measure time it took, if enough then run interaction, else cancel.
@@zORg_alex thanks
That would be the same logic as here in order to identify when objects are in range, but then instead of calling the function on a KeyDown you would maybe increase some float timer while the key was held down and trigger the interaction after it goes above a threshold.
Or look into the new Input System and look at the Hold interactor which will trigger the performed event only after that hold time has elapsed unitycodemonkey.com/video.php?v=Yjee_e4fICc
Please add subtitles if you can. Thank you for the wonderful video. :)
The RUclips auto generated captions are usually very good!
Thank you 🙏
Hey!CodeMonkey,I got a question,how to make two NPC say different things?
Unity newbie here. This probably might not be the best video to ask this but can I ask how can I create NPCs?
It depends on what you mean by NPC. What do you want it to do?
It could be as simple as a game object with a character standing Idle, or something complex like a Companion that follows you and fights. Both are NPCs so it really depends specifically what you are trying to do.
@@CodeMonkeyUnity Just someone (or something if it's possible) to interact.
Thank you so much for the tutorial! It helped me a lot.
Maybe someone here can tell me how to make the player also turn his head towards the NPC? I would be very grateful
Look into IK Inverse Kinematics, Unity has Animation Rigging ruclips.net/video/LEwYmFT3xDk/видео.html
@@CodeMonkeyUnity Thank you very much!!! ♥
Unfortunately after watching that video I still don't understand how to set the target via a C# script...
You set up the IK to follow a transform, then through code you position that target transform wherever you want, like what I did here ruclips.net/video/UL2EbxqwozM/видео.html
@@CodeMonkeyUnity Thank you! Now I understand. You've been very helpful.
can you make a video of an interactable using unity events
Code monkey I appreciate your work please and please their lots of videos on making multiplayer lobby, in game inventory and shop system.
But if you try to search for shop system for multiplayer in start menu there's non like I don't want to make RPG I just wanna make a game where my players are able to buy characters (cars) and enter game with that character (car) but I don't how to please make a tutorial about it I'm making a multiplayer car race game I want players to buy cars and equip it then enter game with it, please (using netcode or photon)
I love you Code Monkey
Thnx ❤
6:30 leaving mark
Put the distance check on the NPC's the player object can talk to.
Why?
@@ewwitsantonio Reduces the complexity of the design, and it is not the Player who should know which NPCs it communicated with; it is the NPCs who should know they need to communicate with the Player.
Doesn't make sense for the NPC to test the distance since it is the Player who is attempting to initiate the interaction, that would only make sense if the NPC was running towards the player to initiate some conversation or give them a quest.
And like I mentioned in the video doing a distance check would be wasteful so that's why I prefer using a simple Physics query.
@@CodeMonkeyUnity Proximity gets tested on collisions. Both objects get tagged. The game shows the conversation via a scriptable object driver conversation using both tags. This is an Object-Oriented Design. For simplicity, you could smush the logic into the scriptable object; however, this would be less Object-Oriented than the other.
@@CodeMonkeyUnity Physics query is only faster because the physics system probably has some kind of chunk-based batching built in. It's quite trivial to implement and would most likely make distance checking faster.
Damn, I thought this tutorial was for IRL.