Тёмный

Unity Interfaces vs Abstract Classes - Part 1 - Interfaces 

Подписаться
Просмотров 67 тыс.
% 2 033

Check out the Course: bit.ly/3i7lLtH
-------
A brief discussion of the differences between Interfaces and Abstract classes in c# when it comes to Unity. Learn when to use interfaces and when to use abstract classes along with the benefits and drawbacks of each.

Опубликовано:

 

11 сен 2017

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 70   
@FlipYourLearning
@FlipYourLearning 3 года назад
Oh, this was so helpful. After a while this video finally made it click for me: interfaces can be used (among other things, probably) when you want to call a certain method from a certain object but you don't know what exact script of the object will have the method. I'm imagining a fireball that could damage a player by calling a method on its health script, make something explode by calling a method on one of its scripts, and make something else simple catch fire but not be destroyed (by calling a different method on a different script of that burnable object). With interfaces, I simply choose one script, already on the objects that could react to the fire (or alternatively make a new script that I would attach to each object), and make that script inherit from an interface (like IFireReactive), and make that interface have a method (for example Reaction). Then, each script inheriting the interface defines what it does when the method is called. In my fireball, upon hitting anything, I get the component IFireReactive of whatever it hit and call its reaction method. Then each object does whatever it was coded to do. That way I can have one script for all things with fire and one script for all things reactive to fire, with no internal conditionals. The fireball or anything else with fire doesn't need to figure out what is hitting to make it react a certain way or call the right method from the right component, and the script that will react to the fire doesn't need to figure out what object it is in to decide what it does. Basically, designing with interfaces in mind instead of without using interfaces can save you code complexity and trouble later on when you want to expand your systems or start changing things.
@ardaozler631
@ardaozler631 3 года назад
thats a great explanation thanks mate
@stbny4444
@stbny4444 2 года назад
this is what I don't understand though. I write a class with an interface inheretance like IDamagable right next to monobehavior. And then you need to define the function below. Well if you didn't use an interface you'd have to do that anyway so the interface doesn't provide any benefit. You can just make a public function, create an instance of the class that the function belongs to in the script that attempts to call that function and it's literally the same thing.
@UltramarineAfterglow
@UltramarineAfterglow 4 года назад
I have a cold. it's a few hours before the New Year 2020. i'm all alone and learing about Interfaces. Live is good :)
@ugurardin4256
@ugurardin4256 4 года назад
You are lucky , because you didn't celebrate the fuckin 2020 :D
@brianpangburn5573
@brianpangburn5573 6 лет назад
Your videos are completely changing the way I do things for the better. When I can afford it, I want your master classes!!
@heyjeanwtf
@heyjeanwtf 5 лет назад
You just saved my life. I ran through the whole internet trying to find a way to "access a script without knowing its name", and Interfaces seem to be the way! I'm making a turn-based strategy game and all I wanted to do is to grab into the GameManager the script of whichever gameobject I click on. Thanks a lot!
@TannerHartwig
@TannerHartwig 4 года назад
2:34 - "I'm gonna make this public... mmm, nope I can't do it" I'm cracking up, I feel your pain. Even in a demo script just can't break from good OO design hahah.
@supercyclone8342
@supercyclone8342 4 года назад
Yeah, I wouldn't have been able to do it either... ha ha... ha **looks over at mega class full of public variables***
@blossumgames9443
@blossumgames9443 4 года назад
Hi sir, I'm a newbie and have been using public variables so I can just tweak them in inspector. May I know what is the difference in using public and serializefield variables aside from making them visible in the inspector ? thanks ^^
@martimking1craft
@martimking1craft 3 года назад
@@blossumgames9443 public variables can be changed in other classes using GetComponent() private can't
@edman3d593
@edman3d593 7 лет назад
As someone who has watched shit loads of tutorial videos about everything, this is a fresh new channel taking on some less popular topics (not necessarily this topic but others). Videos are great, my request for a video is adding high quality lighting to a 2D game in Unity.
@Unity3dCollege
@Unity3dCollege 7 лет назад
Thanks! Adding that to my whiteboard now. I've seen a lot on lighting in 3d, but never thought about doing one on 2D, seems like a fun topic :)
@edman3d593
@edman3d593 7 лет назад
it has to be one of the most scarce topics in Unity. Any decent video on it will be a top video with a lot of views.
@orchard800
@orchard800 6 лет назад
+1
@damaomiX
@damaomiX 6 лет назад
edman3d There are some great asset for 2D lighting, like SF Soft Shadow 2D (payed), Light2D (free), etc.
@spiral9316
@spiral9316 5 лет назад
Yes, Jason is a Rockstar!!!
@aldigangster123
@aldigangster123 5 лет назад
You did, what for some reason I could not find anyone else to explain properly (not even my paid Udemy courses). How to properly call something on another object, who implements the interface, without having to know about it. Thank you so much! Subscribed.
@mykilpee
@mykilpee 6 лет назад
As a massive fan of abstraction in my code you have taken possibly 2 or 3 classes of look-ups and simplified everything and saved me days of work. Thank you so much! I'm a dangerous but knowledgeable coder, so in a month after changing my code around and adding more features if you can show me how I can create a pointer to a char and cast that to a bool in C# OR even tell us how we can build and call some C++ functions (some from other C++ libraries) I can create a feature to make some fun as hell saved games in some fun and exciting formats.
@lux2640
@lux2640 5 лет назад
You teach really, really well. Thanks for everything, man.
@burchmore5000132
@burchmore5000132 7 лет назад
The one thing I consistently have the most trouble with in Unity is the overall architecture of my code. Everything ALWAYS ends up becoming a tightly coupled monolithic structure that is impossible to extend beyond a certain point. Here is an example of the kind of problem I end up encountering: - UI. Should my UI 'observe' the game logic it's representing and update itself as it's own thing (and have the game logic/objects be oblivious to the UI), or should the UI be directly updated from the game objects that it is supposed to represent. I imagine it would be the former, but then I run into issues, like; how do I ensure the UI is aware of game objects that get instantiated or altered at runtime AND require UI representation without those game objects actively updating the UI or being at least somewhat aware of the UI in order to notify it that it exists. Inevitably what ends up happening is my UI gets controlled by the game objects in order to solve the 'awareness' issue and to satisfy all the different types of UI behavior I want, and then I end up with bugs that relate to the UI being controlled from multiple places (eg. if I have other 'global' scripts controlling UI visibility based on the game state, as well as UI being controlled by the individual game objects it's representing). Do you have any general tips or pointers (tutorials etc) for info on how to solve these more broader 'architectural' type problems?
@Unity3dCollege
@Unity3dCollege 7 лет назад
This is a great question, feel like it deserves a video of it's own. Adding that to my board now, will get it up asap
@16nitro78
@16nitro78 4 года назад
Jason Weimann Hi Jason, so did you made a video about the question above. I’m really interested in that topic as well.
@magnusm4
@magnusm4 4 года назад
For the UI problem. Summarized below. The thing I learnt from a video is that visual stuff should listen in on logic like the player's health. First you make the player's health a Scriptable Object so it never vanishes. Second the currentHealth is a get set variable. The UI is on the player's gameObject as a component hence you simply get the Health Scriptable Object regardless if the player exist or not. Thus the UI and anything is not prone to error if the player is erased or disabled and the player's Health or other components doesn't rely on the UI component or sound in any way etc. Now for the update of status part. Use a delegate in the player's Health which is triggered every time the player is hit which takes in a value. Do this by making the currentHealth's set or damage function Invoke the delegate every time the set is given a value or the function is called which is then added to the currentHealth on the Health script. You can also use an Interface that enemies or anything calls for the first time to get the player's maxHealth and currentHealth. This means anyone can get the info off the player and get updated without the player actually knowing about it and if the player is deleted or disabled then nobody throws an error as they don't directly contact the player to check their status and simply their function is unsubscribed, it doesn't even have to be, it still won't throw an error. When the UI or sound component is created it subscribes a function to the Health delegate. So every time the player is either healed or damaged, the Health Scriptable Object will call the functions automatically so no need to constantly check up on the currentHealth. The function in the UI checks if the hit value is negative or positive. If positive it will play heal particles based on the amount, if negative it will show damage particles based on the amount. This value is then applied to the health bar which goes down or up slowly to the new value. It then calls another function to see how low or high the currentHealth is. If low enough it shows flashing effects, if it's too high it shows over heal effects. Don't forget to unsubscribe the functions if the UI or sound component is removed or disabled. SO SUMMARIZED: Player's health is in a script called Health which is a Scriptable Object. The Health script has a delegate that is called every time someone damage it. The delegate function takes in a value, which is the damage the player was hit with. Anyone can subscribe to the delegate and call the Interface to get the values to setup. Now anyone can subscribe and get info from the player's Health and have any function or feature do whatever they want with it. Like an enemy whose attack rate is based on the player's missing health by taking maxHealth-currentHealth. Or a sound script which becomes deeper the more a player is damaged. All this is done separately from the player without their knowing and doesn't have anything to do with it. This means you can create, add and change out the Ui for a new one or create an entire new enemy who also changes his behavior based on the player's damage taken or their current health and you don't ever have to touch or change the player in any way at all ever. And nobody gets an error if either is suddenly deleted. Cause a Scriptable Object is separate from the game and doesn't vanish or reset in or between scenes. And because nobody depends on the other to exist and only gets their values updated when they change then there's no performance being used up on constantly updating their values by calling the player and getting the values directly.
@shubhamjain54519
@shubhamjain54519 3 года назад
@@magnusm4 wow awesome
@giantswing3175
@giantswing3175 Год назад
I know it's been many years since the original comment but for anyone wondering, at least for me, my answer to many of those questions is just "use scriptable objects" the ui can take a floatSO and communicate with that once it updates and the player can communicate to that same floatSO when the health changes, it decouples your scripts in a really easy way plus because scriptable objects are just assets that live in your project, you can fill those references in the inspector and when you save the prefab those references will get saved, so you can just grab those prefabs and put them in a new scene and not have to worry about the references being lost or having to resolve a bunch of dependencies in awake methods, it really has changed the way I approach gamedev in unity
@spiral9316
@spiral9316 5 лет назад
Watching your videos is like, the first time I went to United States.. everything was like rich and abundant..(compared to my country) You are cool. Like being on a dessert and then I arrive on the oasis.. feels good man. I mean this; i have watched so much tutorials.. Informations and oh my God.. At last i get it!!! Thank you! from my hearth of hearths !! Appreciated
@Spyderislive
@Spyderislive 8 месяцев назад
at last i understood how to do interfacing thank you so much
@Unity3dCollege
@Unity3dCollege 8 месяцев назад
You're welcome!
@antimuffin7
@antimuffin7 7 лет назад
Thanks for the explanation--working on sorting out these definitions and your video was a big help.
@mintydog06
@mintydog06 5 лет назад
Thanks for this video, brilliant, and you work so quickly as well. I wish I knew about Interfaces a year ago, might have saved me some hassle haha. I'm going to implement some now and hopefully improve my game. I really should learn more C#.
@kilianreisinger823
@kilianreisinger823 4 года назад
I finaly understand Interfaces. thanks.
@FuzzyDPozzy
@FuzzyDPozzy 5 лет назад
@Unity3dCollege thank you sir for this incredible video sometimes you make really incredible videos like this, i just want to say after all this words you took your time to read even though i don't know what i am trying to say is that i have no other words to say how grateful and thankful i am for coming across to this awesome epic ultra awesome tutorial about interfaces , i just want to say a big big big thank you !!!
@PicnicsPete
@PicnicsPete 4 года назад
Really clear explanation. Thanks for doing these.
@gdk870
@gdk870 5 лет назад
Hello there, Great video. First time it clicked for me. So where can i get more on this programming related topics? Is this video part of a series/playlist? I'd like to dig in some more. Cheers.
@CanaldoCaverninha
@CanaldoCaverninha 6 лет назад
U ARE UNITY GOD MA-BOY !!
@Unity3dCollege
@Unity3dCollege 6 лет назад
lol thx :)
@giantswing3175
@giantswing3175 Год назад
Before I learned interfaces, I just had a different component that was a monobehaviour that I'd add to any object I wanted to be able to take damage and then invoke an action I subscribed to in the main script of the enemy or whatever it was, in the end it worked really similar to this just that I would get that component in the raycast instead of the interface. I know that having too many monobehaviours is bad for performance but other than that is there any benefit to this? The thing I liked about my previous approach was that I could just enable and disable whenever I wanted that 'take damage" component to test different behaviors which I don't think I can do with this interface approach without having to start adding if elses, am I missing something here? Thanks
@danielrousseau6541
@danielrousseau6541 7 лет назад
you just changed the game for me :D
@Unity3dCollege
@Unity3dCollege 7 лет назад
awesome, make sure to check out abstract classes too :)
@MikeArcuri
@MikeArcuri 3 года назад
Great tutorial! Q: do you see this pattern as a good alternative to using events for things like damage? Or are event systems preferable? Or would you use both interfaces and events in the same game?
@richardosborn3810
@richardosborn3810 3 года назад
Hey Jason, I've tried this in my own project, but it doesn't seem to work. I mean, I watched it work in your project, but I can't seem to get GetComponent to work on Interfaces in my project. Has anyone confirmed this actually works? (I know my raycast is hitting the object I want, but the GetComponent() call always returns null).
@toastyshrimp1882
@toastyshrimp1882 2 года назад
5:05 onward, why does he pass hitInfo into the method via out? My rough understanding is that out is passing the parameter by reference but you need to initialize the parameter inside the method. I don't understand why this is useful or why he chose to do this here, does anyone have any idea?
@TheKr0ckeR
@TheKr0ckeR 3 года назад
Hey, thanks for great guide! What would we do in best practice if we wanted to damage spesific for example "5 damage to car" and "2 damage to barrel"? We are here wont be able to change by it. Maybe we can increase their hp in their class. But what would be the other way? " ITakeDamage damagable = hitInfo.collider.GetComponent(); if (damagable != null) { damagable.TakeDamage(5); // here we damage all Idamagable interfaces } "
@imaginationrabbit
@imaginationrabbit 7 лет назад
Great tutorial- thank you!
@punixerz
@punixerz 5 лет назад
I can only subscribe once bro! Thanks for your work.
@marcus_vdm
@marcus_vdm Год назад
So ITakeDamage is considered a component?
@Mogo-jan
@Mogo-jan 4 года назад
If an interface had multiple methods, they would all need to be implemented right?
@Unity3dCollege
@Unity3dCollege 4 года назад
Yes
@Shadow2Matrix
@Shadow2Matrix 3 года назад
God Bless this video but it breaks the rules of programming in my head. Say you shoot an object that DOES NOT have an interface, line 15 in 8:01 should trigger an error but it doesn't right? Is this interface magic?
@hailelam4112
@hailelam4112 Год назад
Thank you so much
@spiral9316
@spiral9316 5 лет назад
A light shines forth on the horizon. As i understand this problematic concept. Sir.. I tip my fedora; and take damage with a smile.
@RetroGamingClashOfClans
@RetroGamingClashOfClans 5 лет назад
But i can have a script called "Damagable" (with a take damage method in it) a normal class and add to all the damageable objects and check if that script exists and do GetComponent().TakeDamage();
@alexkhazov7264
@alexkhazov7264 4 года назад
That would be the better way to go - composition. Interfaces are a form of composition, but for OOP. They are not very good for game development, and you will only find rare cases where you need them (events, and Unity events specifically, for example).
@alialacan7774
@alialacan7774 5 лет назад
Great tutorial thank you!
@Killer_Nads
@Killer_Nads 7 лет назад
Fantastic Tutorial this!!
@firnekburg4990
@firnekburg4990 6 лет назад
You're the best ! Thank you !
@sakari.niittymaa
@sakari.niittymaa 5 лет назад
Perfect! Thank you!
@F3ND1MUS
@F3ND1MUS 4 года назад
ty
@huseyin.goktas
@huseyin.goktas 6 лет назад
It is super amazing.
@ZeroSleap
@ZeroSleap 4 года назад
I like to think of interfaces,as "Declaring" what they do,for example ITakeDamage if you put this interface in any class it says "Hey i take damage man!"
@shubhamjain54519
@shubhamjain54519 3 года назад
ICanBeDestroyedFromCrash
@kiwiboysl
@kiwiboysl 3 года назад
I've become accustomed to using something more like this. ``` if( hitInfo.collider.TryGetComponent(out ITakeDamage damagable)) {//Do stuff with damagable} ``` This way you don't have things allocating in the Editor when the requested component does not exist.
@zolan4277
@zolan4277 3 года назад
I literally snorted when you tried to make the health variable public and physically couldn't force yourself to do it.
@benzenatizineeddine7816
@benzenatizineeddine7816 4 года назад
i'll die to know how monobehaviour works
@phambaoha170
@phambaoha170 4 года назад
nooooooooooo
@chadamitecheckoutredpillpl2641
@chadamitecheckoutredpillpl2641 3 года назад
its all so tiresome