What are Interfaces? (C# Basics)
HTML-код
- Опубликовано: 12 май 2024
- 🌍 FREE C# Beginner Complete Course! • Learn C# Beginner FREE...
🔴 Watch my Complete FREE Game Dev Course! 🌍 • Learn Unity Beginner/I...
📝 C# Basics to Advanced Playlist • C# Basics to Advanced
🌍 Get my Complete Courses! ✅ unitycodemonkey.com/courses
👍 Learn to make awesome games step-by-step from start to finish.
🎮 Get my Steam Games unitycodemonkey.com/gamebundle
✅ Let's learn all about Interfaces in C# and how they help us write cleaner code!
Get the Project Files and Utilities at unitycodemonkey.com/video.php...
Learn Unity in 17 MINUTES!
• Learn Unity in 17 MINU...
Learn C# BASICS in 10 MINUTES!
• Learn C# BASICS in 10 ...
What are Events? (C# Basics)
• What are Events? (C# B...
What are Delegates? (C# Basics, Lambda, Action, Func)
• What are Delegates? (C...
What are Interfaces? (C# Basics)
• What are Interfaces? (...
What are Generics? (C# Basics)
• What are Generics? (C#...
What are Loops? (C# Basics, for, while, do)
• What are Loops? (C# Ba...
Unity Tips in 10 MINUTES!
• 12 MORE Unity Tips in ...
Unity Basics for Beginners
• Learn Unity in 17 MINU...
3 Ways to Shoot Projectiles in Unity
• 3 Ways to Shoot Projec...
Modular Character System
• Modular Character Syst...
Patreon Sponsor: www.badadventurer.com/
If you have any questions post them in the comments and I'll do my best to answer them.
🔔 Subscribe for more Unity Tutorials / @codemonkeyunity
See you next time!
📍 Support on Patreon / unitycodemonkey
🤖 Join the Community Discord / discord
📦 Grab the Game Bundle at unitycodemonkey.com/gameBundl...
📝 Get the Code Monkey Utilities at unitycodemonkey.com/utils.php
#unitytutorial #unity3d #unity2d
--------------------------------------------------------------------
Hello and welcome, I am your Code Monkey and here you will learn everything about Game Development in Unity 2D using C#.
I've been developing games for several years with 7 published games on Steam and now I'm sharing my knowledge to help you on your own game development journey.
You can see my games at www.endlessloopstudios.com
--------------------------------------------------------------------
- Website: unitycodemonkey.com/
- Twitter: / unitycodemonkey
- Facebook: / unitycodemonkey
🌍 FREE C# Beginner Complete Course! ruclips.net/video/pReR6Z9rK-o/видео.html
🔴 Watch my Complete FREE Game Dev Course! 🌍 ruclips.net/video/AmGSEH7QcDg/видео.html
📝 C# Basics to Advanced Playlist ruclips.net/p/PLzDRvYVwl53t2GGC4rV_AmH7vSvSqjVmz
🌐 Have you found the videos Helpful and Valuable?
❤️ Get my Courses unitycodemonkey.com/courses or my Steam Games 🎮 unitycodemonkey.com/gamebundle
Let's learn all about Interfaces in C# and how they help us write cleaner code!
Could you recreate games you made, from scratch? like, the exact same game from scratch.
I've used Unity for around 6 years now and every time I bumped into interfaces, I dismissed them. Seeing them depicted in this way and with a real use case made me better comprehend how useful they can be! Thank you so much for the great tutorials.
I have been trying to understand interfaces for SO LONG. Every single video about them seems to skip over passing objects that implement interfaces into methods. Now knowing what they are used for, that was KEY to understanding them. I seriously could not figure out why they were useful because it seemed redundant to define a method in a separate place instead of where you were using it. Thank you, seriously.
I'm glad the video helped you! Thanks!
There seems to be 2 kinds of failing to understand something in coding
The traditional one, we're all familiar with is - _"I didn't understand the words you used, and I couldn't recreate what I saw on screen, because I got it wrong"_
But the far worse one (and I struggle with this all the time) is _"it's completely clear what you did, I can totally recreate that, but I can't for the life of me work out the value of doing that."_
Thank you for this video that cured me of the second type!
So far the best explanation I've seen for interfaces and I finally grasped what these things are doing.
Thanks a lot!
Straight to the point, and the damage example showing in practice how to use it makes it very easy to understand. Definetly learned something useful from this and will change my code right away. That's why this video is the top search for "unity interface".
Thank you for making these clear and concise tutorials. You are great at it!
"C# Basics to Advanced" is awesome! Many have (including me) a problem understanding the concepts and how they can implement them to their game.. You cover both! More examples of implementation (problematic vs correct) would be great. Thanx for the help!
Your didactics never cease to amaze me. Thank you for not only explaining what it is, but also showing us where it can be useful!
Best understand explanasion about Interfaces I ever seen. Thank you a lot!
I love Object Oriented Programming, I used to hate interfaces because I didn't understand them properly, but this video helped make it clear as day and I will be using these all the time from now on! Thank you.
i was expecting this. thank you for your awesome tutorials.
Hey Code Monkey !
First of all, thanks for all the effort you have put into this channel, it's great to find people like you ready to help and teach learners! Your channel is kinda my Bible, anything I need, I come here first and most of the time, you answered my question! So thanks you for that and big shout-out for your games, they are great!
I also had a question: do you have any tip for learning how to make visual art?
I'm teaching myself about videogame development and if, as a computer science student, code isn't much a problem, art is. I haven't any artistic background and I have trouble making proper characters sprites, scenery, etc...
I really like the style you use in your games with only a head, a torso and a pair of hands and feet. It seems easier to customize than making a full body everything.
The visual is what makes me drop every project. I know I could find pre-made packs online but it feels like the game is no longer mine if I use those...
Thanks for everything and have a good day!
Guillaume.
Just another video that has dramatically taken away extra lines of code, and simplified my project! I enjoy seeing everything applied and how everything becomes much more scalable.
I just have just one question ... how on heaven and Earth do you code so fast? Not just typing, but navigating from line to line, cutting and pasting lines, inserting functions etc. It's mesmerising.
It's all about experience! I've been writing code for over 20 years!
Haha you know it's sped up for most of his typing right?
@@jahwni He's not talking about those parts lol
You just gotta learn the shortcuts. They're like magic!
@@CodeMonkeyUnity hello. What’s your take on Interfaces vs Components? It can be HealthComponent instead of IDamagable interface. Component provides implementation but complicates communication(between components of the same gameObject).
Excellent, was slightly puzzled by Interfaces and with your clear explanation it now makes sense.
Awesome video, thanks!
These practical examples are very useful, because it helps ua give the basic idea on how we can implement it by ourselves.
Now that's what missing at most of tutorials, they just explain it no practical example.
Thanks again!
Another way on how to use Interfaces in unity is to define an Abstract Scriptable Object that implements the functionality of the Interface.
The clases that implement the interface then have a Serialize field where you can drag in the concrete implementation of the scriptable object.
And you implement the interface by calling the function on the scriptable object.
I even got so far to make a propertyAttribute that uses reflection to show all classes that inherit from the abstract class in a dropdown and automatically creates a scriptable object for me.
You can go really complex with that and you can easily switch between different behaviours just by using a dropdown menu.
And the best? if you want to add a new function, all you have to do is to create a class that inherits from the abstract scriptable object. Done.
thats pretty clever lol
To be honest that's super useful, I never thought about it
@@noargames6628 It really is a gamechanger for me.
And once you use it, you realize you can do a lot more like allowing objects to talk with each other just by sharing the same object
@@huyopo Hey, could you elaborate a little more please, I'm having trouble understanding this implementation
@@debugdotlog7745 well, the key part is a method that gets all derived classes from a base class you can easily find that using google.
And with that on hand you can make a custom property drawer that shows a dropdown menu with the contents from that method.
And if you choose an option it can automatically create the scriptable object for you.
If you know editor scripting it's actually not that hard, if you don't know it then learn it its really useful.
If you don't get that, you can skip it and just use it with drag and drop.
The rest is pretty much an implementation of the strategy pattern. The Monobehaviour implements the Interface and the interface method calls the method on the scriptable object.
So like this:
Class Entity:MonoBehaviour,IMovable
{
[ScriptableObjectDropdown]
MoveableScriptableObject moveScriptable;
void Move()
{
moveScriptable.Move(transform);
}
}
abstract class MoveableScriptableObject:Scriptable Object
{
public abstract void Move(Transform transform);
}
And then you can write a lot of derived classes from the Scriptable object and you can easily switch between them via dropdown.
I love this video. As a game artist trying to learn C# I need to see how my code works and what it is capable of, the example with the 3 different objects truly creates an Aha moment in my brain!
i have never been this excited to use something i learned in my life thank you
Thank you, I had a really hard time understanding interfaces. When I started the video I was completely lost, but with your example everything became really easy! You should keep making examples after the teaching part!
Finaly I understand the usage of interfaces. Thank you for good lessons!
I started really few days ago and every topic I watched , really nice explanation and simple examples.Thank you for prepared these .
I want to thank you, man. This is one of the best videos I have seen on interfaces, not just because you explain how it works but you gave a concise use case that is common.
I never thought that I would find a non-esoteric use for interface but I am glad to be proven wrong and to incorporate interfaces in my own project.
Thanks! I'm glad you found the video helpful!
This was so good!!!! Thank you bro!!
I have knowledge about interfaces since college days but never had easy and realistic example like this.
Now I would definitely go crazy defining lots of Interfaces, Thanks CM
No matter how basic your videos are, they are always helpful in one way or another
The fucking backhanded compliment at the end was so unnecessary holy shit
@@sleepsleeper4466 I don't think he meant it that way
Very good explanation. Easy to understand and to follow along. Thank you very much!
This is extremely useful! Thanks for the tutorial!
Last tuts I checked about Interfaces showed no example or implementation using an Instance game object so I was left wondering why in hell I would ever use Instances in the first place.
Great video that explains clearly with a real case scenario!
This was very helpful, thank you.
Cool stuff! Great C# tutorial! 👍🤓
oh man....your tutorials are taking me to the next level lol, my whole game project is(was) made up without the use of interfaces and generics...thanks for these tuts and the courses on udemy!
Very helpful! We use interface for OOP in Java but I never knew how to implement them in Unity C#
Your video format for tutorials is perfect.
Brief description of topic in intro.
An overview of what you'll talk about.
Teaching about the thing.
Practical example of thing.
It's ordered in a clear, concise manner that is captivating, and flows naturally every time.
Thanks! I'm glad you like it!
@CodeMonkey
I use your videos 10x more than Microsoft's own documentation.
My brain struggles to remember certain things (product of being a degenerate addict in my youth)
so I always come back to reference certain things using your videos.
Great video as always, would also like to see a video on the new animation rigging package.
Thanks for showing a realistic use case. The problem I had/have with Interfaces (bar newest C# version with an ability to define a default implementation, like you've described) is that you actually do not avoid copy-pasting entirely, because you have to implement the interface in each class anyway. Most of the time I found inheritance/overrides (polymorphic approach) to require less lines of code. But that's not always applicable and not so flexible/extensible as using interfaces, of course, since you need to figure out your tree of inheritance beforehand and then stick to it. Thanks again!
BOOOM! Love it!!! Literally asked for this today =) thank you
11:30 in and It just clicked!.... Wow, this is powerful!
Now I see why interfaces are used! Thank you! Could you do a video about how data structures are used in game dev please? (LinkedLists, Queues, Stacks, HashMaps, etc...)
i am a beginner in c# and got so amused by this use case of interfaces , you are setting my expectations high from youtube videos ❤❤❤❤❤❤
For the first 9 minutes of the video I was clueless of what was happening. Wondering why would I even use this or how. Then you started the example and it clicked. This is exactly what I was looking for. Thanks
Thanks. Your videos are well explained and it's good that you show examples how to use the stuff you teach
Thanks! I'm glad you found the video helpful!
This made it finally click for me!! Thank you!
Interfaces look so easy to implement, I'm definitely gonna use them more and write cleaner code with them.
Thanks, very helpful for me as learning game dev :D
I find u everyone Dave :D
@@signalised9540 Haha... I'm where the other gamedevs are :D
Another one of those great videos by CodeMonkey and the best one out there to understand interfaces. It's very concise and to the point as a whole, but the second part of it (08:30 onward) is like PURE GOLD. Not only is it demonstrating the theoretical purpose and usefulness of interfaces, but also giving a clear, real, no-bullshit implementation example.
Thanks! I'm glad you liked it!
I spent the last 2 hours searching the web for how to see if an object contains a interface of a particular type similar to what you showed except through ray casting. After watching your video I confirmed I was executing my code correctly and it should have been working the way I thought it would have (for example being able to do TryGetComponent) When it didn't work I thought maybe you cant do that since its not the classes direct name but you confirmed my thought that you can. Then I noticed it was because I had a box collider on the object and not a box collider 2D. (Im making a 2D game) And that's how I wasted 2 hrs of my life.
Heh that happens, good news is the next time you come across a similar issue you already know what might be the problem!
Thank's a LOT for this video!!! 👍
Thank u Mr, usually I can't find anyone else u can explain in an easy way.
I'm glad the video helped you! Thanks!
Found this channel, I am exited to learn new consepts. Seems like this guy is quite good about explainign things, I am sure it is not easy task to explaing how to write a code for a some codemonkey like myself XD
This tutorial is very helpful. Now I'm the fan of your channel. :)
Wow!!! Thanks sir for the video. 😀👍🏻
Thx for your videos they are great :)
Amazing just watched two tutorial from you and it helped me out tremendously, just because you show real use examples.
I mean interfaces seemed easy but I asked myself "what am I gonna use them for?" After your example it's much easier to find real use for them
Same for your delegates tutorial!
Subbed and bookmarked your channel, thank you.
Time to edit some code.... x)
I'm glad the videos helped you! Thanks!
Quite interesting! Thanks Hugo!
just cool, into the unity, nice!🙌🏼
YOU MAKE THIS SO CLEAR !!!!!!!!!!!!!!! xxxxxxxxxx
Excellent explanation 😁
Awesome, thanks for sharing
Hi. Your channel helps a lot to beginner. Best unity channel.
I love you. When I'll have some spare money I'll reward your kindness. I was missing just this bit for so long... If I only found out about it earlier I pobably would be a proper gamedev by now...
Amazing tutorial!
Thanks , it's helpful
Interfaces are interesting and I've been wanting to try and use them for awhile, but I haven't found a good use case yet in my projects. Usually I have this stuff covered by inheritance or a component style approach. In your example instead of an interface, I prefer having a health component that only deals with health. And it fires off C# events for things like taking damage and death. Other components can listen for those events for customization purposes.
I really need something like this because I'm planning on making a bunch of characters with different scripts but the damages and knockbacks needed to work the same for everyone.
The first examples are so confusing I wanted to give up and just do the "everyone will share the exact one script" mindset, until I reach the part of the video with actual implementation and it's much easier to understand.
beautiful, thanks
Uau. Agora entendi a importância de interfaces! Fez meu dia terminar com chave de ouro, muito obrigada!
if your struggling to follow along as he is explaining like i did because he talks really fast while explaining like this class uses this interface which uses this function and start to get confused then changing the playback speed to 0.75 speed and sometimes pausing to think helped me to eventually grasp interfaces :)
best video ever on interfaces ,thank youuuuuuuuuuuuuu
I'm glad the video helped you! Thanks!
Very Good Tutorial!! EZ 2 understand
I like interface working togetter with a abstraction. you can make really powerfull things out of it.
i have fear to learn interfaces but when i watch your video then its gone, and i also started to loving interfaces as well as your flow of teaching that, thank you so much sir
I'm glad you're no longer afraid, they are an excellent very powerful feature!
Just to say thanks and tell you, this way of teaching is really good for many reasons, not only explain the definition but also showing a real case scenario and after watching and searching other videos, this one is still the best one and easiest to understand, i do have watched your explanation about events and also delegates, but i forgot it sometimes and keeps coming back, so just want to say thanks for all the works you do, and i hope you found your success in your current project, and also i want to ask about planning for the future, any new paid course in udemy, i really wondering how to create the chart in your blueprint steam game, and how to manage those data, I've tried to make something similar but ended up a mess, i knew you are busy these days, and yeah I'm just mainly want to say thanks. 😅
It's perfectly okay to keep coming back as long as every time you come back it's easier to remember how it works.
For example there are some things, like how to read a file, that I just google everytime because I never memorize it, but a quick google instantly makes me remember
Hi im french Canadian and i just want to say you helped me a lot, thank you!
I'm glad to hear it! Thanks!
@@CodeMonkeyUnity No problem
This makes so much sense in Unity but I still have trouble grasping practical uses of interfaces in other coding situations outside of game making
Wow, so powerful!
Yeah I already knew what are interfaces and how they work but still like this video
Btw I can't wait until unity support c# 8 :) It will be awesome.
Thank you very much
I never really had to use interfaces, didn't see the point of using them - until now! I had another system in place for my game (unity events) where the player can look at objects (FPS game) and interact with it using a mouse click if the gameobject had an 'interactable' component attached to it, I ditched it because now I totally understand interfaces now Code Monkey thanks to you - no one else was able to properly explain its purpose - I implemented it and my code is so much cleaner now!! (cut out like 50 lines of code), thanks again!
That's awesome, I'm glad the video helped! Thanks!
Thanks!
Awesome Content
Hello Code Monkey! Thanks for the great tutorials man! I just had a curious question. At 11:45 you got the component even though you did not attach the IDamageable script to the gameobjects. Since Unity did not detect a "IDamageable" script component, does it try and get any other script in that gameobject that has inherited that "IDamageable" script? (in this case the "Enemy" or "Crate" script components) How does it work exactly? Also I am loving your Builder Defender course so far, keep producing great content!
You cannot attach an interface directly since an interface isn't something you can instantiate by itself, instead you attach some script that implements the interface.
Then using GetComponent it checks if any of the attached components implement that interface.
I'm glad you're enjoying the course! Thanks!
Thanks for asking this, I was gonna ask the same question haha
Thank you!!!!!!!!!!!!
Thank you for the video. It would also be much appreciated if you could make a video where you use interfaces in implementing a state pattern. I often end up with a character (or some other state-having game object) that has a ton of interface implementing Monobehaviours attached. And each state just calls the interface not knowing that its implementation is specific to said state. To make a long story short, how do you approach interface use in state management?
Check out the Modular character video, it uses interfaces with various implementations to do just that ruclips.net/video/mJRc9kLxFSk/видео.html
@@CodeMonkeyUnity So i watched the video, very helpful. Though, i'm still a bit unsure about how you would comfortably handle various (say 20) different character states though. Perhaps have 20 child game objects with a state specific interface implementations attached? Then disable the currently enabled child when leaving "that" state, and enabling the child whose state should be assumed? What are your counter thoughts?
Thank you
Quality top as always(Y)
With interfaces it isn't even "inherit" anyway, you *implement* interfaces, not inherit from them. C# is still only a single inheritance language, but it allows you to get around this limitation with it by implementing multiple interfaces.
good job!!
thank youuu
To help understand the concept of interfaces:
Interfaces are like middlemen for class dependencies. You don't have to worry about breaking dependencies when you change or switch out a class it depends on as long as it implements the same interface. The dependency just needs to know how to use the interface to get what it needs. It doesn't care how that output is produced as long as it works. When a class has implemented an interface, you know what methods to expect from it and if you ever delete one of the methods it will throw an error to ensure the agreed upon methods are being used (errors are caught immediately at the source instead of at runtime wondering what happened).
Analogy:
A DVD player and a blue ray player work differently yet expose the same interface (play, stop, fast forward, etc.). This way, the user doesn't have to know what is going on inside the machine. As long as they understand the interface, they can get the desired output (the video). This way they can switch out a DVD with a blue ray player and still get what they want.
Pretty bad explanation sorry. You used a lot of jargon. And the analogy doesn't really work. The best way to understand interfaces is to go make a finite state machine using them.
I love your vids.
It would be cool tutorials with design patterns, code principles. KISS, SOLID, DRY, rarely see those in game tutorials.
@Violet twd, keep it simple sucker (that's the actual name)
Thank you Code Monkey!
I thought that components need to be separate "things" that are added to a game object and we can see them via inspector. The bullet checks for a component and finds the interface IDamageable even though the object does not have the script added in a way that we can see it on the inspector.
Is Monobehaviour also a component then?
MonoBehaviour is a Component, an interface is not a component but if a MonoBehaviour implements it then you can write code against it
Awesome! Anyway can you explain on how to use struct and when to use it?
Sure, I covered Classes vs Structs here ruclips.net/video/KGFAnwkO0Pk/видео.html
Please do a video on integrating admob to our games
Well, I needed to do something similar on a project, so what I did is creating an abstract class "interactable" for all the objects that the player can interact to by pressing the "E" key. That class only contains the definition of interact() that is called in the same class with OnTriggerStay2D. I made a special script for every object which inherits from "intercatable" class that overrides interact() sinc every object has a diferent response to the player interactring with it. Which is the difference between doing it like this or with Interfaces? I guess that is just that you can inherit from multiple interfaces but only one class.
The best split is, subclassing should be used if the subclass is "All of this but extra" and interfaces should be used in the case of "This but differently". It becomes a lot more clearer if you think of something like. An inventory of IinventoryItem with a .Use() function. Potions, Weapons, Food, etc are all a good fit so you can do something like "when I right click an inventory item, use it as an IinvetoryItem.Use(). Potions implement that increasing health, weapons auto put it on your character, etc. There's no need to differentiate between different kinds of inventory items then. If this was a sub class it wouldn't make much sense since they all do very different things besides this one small bit of functionality.
Yup the main limitation is you can only extend a single base class as opposed to implementing as many interfaces as you want.
I did use a IInteractable interface in the Doom game and the methods to open doors, on my Player test for the interact key, do a OverlapBox to get colliders near the player, do GetComponent() and if so call .Interact();
Very easy to apply that to toggling a button or opening/closing doors
Could you do a simple program that uses interfaces. Generics, polymorphisms, and delegated? When and how to use them. Do you have training courses for your game built from the beginning?
very cool feature
Wow 🤩 ❤
First of all, thank you so much for enlightening about interface. It's so useful. I am curious about if we want our bullet does different damages between player and crate, do we have to set it in player and crate scripts or we can also implement it just in bullet script?
You could modify the interface to add a parameter on the function
void Damage(int damageAmount);
Then customize that damage amount on the bullet