UNITY MonoBehaviour Basics

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
a monob behavior is a C class that you can inherit from and it makes it a lot easier to write code for games a lot of the stuff you don't even have to write yourself it's just going to be there and you can just use it mono behaviors are added as components to game objects so if you select a game object look in the inspector to the right you'll be able to see if it's got a monob behavior there you can manually drag and drop a monob behavior onto a game object and you can do it during runtime as well with game object. add component and you can destroy a mon Behavior with object. destroy stay till the end of the video where I bet you I'm going to show you some of the methods that come with a mon behavior that you didn't know about or that you forgot about all right so let's dive in and look at mon behaviors and see what type of methods that we can make use out of in our games I'll enable this life cycle Cube here in the inspector make sure this game object it's just a cube with a renderer and a box collider and I've got this monob Behavior script that I've created and I've added it to it and we can double click on it here to get right into the editor and we can see the most important thing is here that it says colon monob Behavior after the class de cation and that means that we're inheriting from mon behavior and that comes with a lot of goodies that we can make use in our games and a few of the first one we're going to go through are these things at the top here and you don't override these you actually just write them like you declare normal method in C so private void awake and we've got private void on enable and start and it's a bit tricky to know exactly what these are called so you can look at the unity documentation for monab behaviors and you get a really nice condensed list there and you can actually figure out a lot of the cool functionality that you can get from this let's start by just running this and see what happens and it's not going to do much this Cube exists here and in the console we can see that a wake was called we see a un enable was called and we see that start was called and this order is very interesting and very important here a wake is always called First on a game object if you got this mon Behavior awake will run and then on enable will run because it was enabled and then start is run and you might wonder why there are multiple of these things why wouldn't it be just enough with a wake and it's because if you've got multiple game objects then all the awake methods are called on all of those game objects first when that's finished all the UN enable will be called and when all of those un enabled are finished then all the start will be called because sometimes it's important to put stuff and initialize things in awake because you want to make sure that by the time you get to start all the game objects in your scene will have run this awake function it's used for example for game managers if you want to instantiate a central object that's a singl ton and you can you want to reach that if that makes no sense that's perfectly fine don't worry about it just know that it's pretty good to have this actual additional places to stick it in and start is the one that Unity usually recommends it comes predefined in the scripts because it's so commonly used but be aware that you've got the the awake and un enable here to do as well so if we go back into our little script that we had here basically it just executes this one for the game object with a mon Behavior it executes this one and it executes start and all I did here was just throw some stuff out in the debug log I've also got a few other ones that are very commonly used here like update and late update and fixed update but we're going to be focusing a little bit on this undisable as well and when you declare this one in a Mony Behavior this undisable will automatically be executed if you disable either the game object itself that has the mon Behavior or the mon Behavior itself and we can actually look here if I'm running here and let's just disable this now I can actually untick this here in the inspector and you can see that on disable was executed and if I enable it again then un enable was executed and this is a useful Place un enable and undisable for example if you need to subscribe to events that are happening in your game then you might want to subscribe to them when un enable is executed and when the game object or the mon behavior is disabled you want to unsubscribe to that event so un enable and on disable are very useful here even if I disable the entire game object you can see that undisable was called because it's automatically disabling the whole hierarchy of this game object if I if I enable it again then we've got another entry here that on enable was called all right so with this life cycle I actually put a few more lines of code in here and we can see in the update update method here that's also a monob behavior method and this one is called every frame of your game that means that every frame whether it's running 60 frames per second one frame per seconds because you got like a super old computer from the late 80s or something and you've got a super fast computer runs to like 200 300 400 frames per second well this update method here is going to run every single frame and this is very commonly used inside when you create a game and I've created a little code here because one of the most important thing is that you want to read any keyboard input in the update method here because you might miss it otherwise if you hit the key here I'm I'm checking if I've get key down here and see if I'm pressing alpha numeric one here on my keyboard and if I do that it's going to enable this mon Behavior or it's actually going to toggle it it's going to if it's enabled it's going to disable it and if it's disabled it's meant to be re-enabling it and and if I press number two on the keyboard here then it should destroy the whole game object and we can try this in action now so I'll press play and we'll say okay what happens if I press one okay undisable was called that means that on when I pressed one I read it in the update because it runs every frame it's not going to miss that key press that I just did and when I clicked it then it actually disabled this mon behavior and I wrote the code here if you remember correctly now then well if I even remember correctly myself then it should actually toggl it back on when I press it again because it to this to the other state so if it's disabled or if enabled is false then it should put it back to true but this is not going to work and I wonder if you know why if I press one again it's say o okay it's not updating why it's not happening and it's because this mon behavior is disabled and when it's disabled like this then the update Loop doesn't run so it's actually not in here and that's very important to know if you disable a mon Behavior or the game object a few of these methods won't execute so the update it's very good for performance reasons and also you don't just don't want the objects to update if they unless they really have to so that's why you cannot toggle it back on in the same way like this and we can also destroy the whole game object if I press number two here make sure this on is enabled I press number two and it just destroyed the game object and instead of destroying the game object we can actually do this we can change this to this that means actually this particular Mony Behavior so if I minimize this I press play again and we go okay here's my life cycle Cube I press I'll select it first of all so we can see it and we see that we've got the mon Behavior here I press number two and I've just destroyed the Mony Behavior so you can destroy them too if you want to remove a Mony behavior from a game object like this okay let's move on to the second one we've got this update Cube so let's enable this one and we've got a script on this one it's called the mon behaviors update that's just the name of it and if I double click what's this one doing first of all it's inheriting from Mony Behavior very important and then it we've just got the update Loop of this remember it's called once every frame and what are we doing in this well we're moving the object forward by one unit oh no actually we're not moving it Forward we're moving it right one unit per second so transform. translate means that we're moving it and we're moving it in the vector 3. right direction and here is very important you have to multiply it by time. Delta time because we don't really know how many times we're getting into this update Loop it could be if you're running 60 frames per seconds it's 60 times per second so it's very important to multiply by time. Delta time so we get a little fraction of a second there so we know how long was it since we were in this function last time and then input should always be PED in this one so make sure if you're going to read keyboard input or button input put or anything like that put it in the update method and here we go okay if we press space it's going to reset the position of this transform back to zero so let's have a look at what this does now when I press play we can see we've got this update Cube and it's moving to the right at one unit per second okay and what happen if I press space it just resets it so make sure any movement code or if you rotate or scale an object continuously that should go in your update Loop and if you read input from your keyboard that should also go in your update Loop remember that all right so the next one let's have a look at some of the monob behavior methods that comes with physics so let's enable this one called physics Cube and we've got a pretty similar but I've got a rigid body attached to this one which is a physics component and we can have it use gravity so it falls down let's look at this script and what do we have here we've got something called fixed update so it sounds a little bit similar to update right but fixed update is different from update it runs not every frame it runs every time the physics engine updates and that by default runs 100 times per second in unity you can change that but I don't recommend changing it because it's going a little bit quirky if you change it I don't think it's meant to be changed so 100 times per second this physics Loop is going to run and if you run a game runs at 60 frames per second well then you're going to actually have more physics updates per second than you're going to have uh frames per second or rendered frames and if your game runs at 200 frames per second it's actually going to render a lot more frames than it's going to do physics updates so fixed update is called once per physics update which runs 100 times per second by default and what I've done here is I'm adding a force here of physics. gravity but negative and then I'm using just the Force Mode acceleration here so every fixed update here I'm applying basically the gravity but in the other direction so this Cube here should be suspended in midair and also I have to make sure that I can reach the rigid body and that's why we've got this serialized field rigid body RB here that's because I need to drag this reference to the rigid body so I can actually apply the add Force to this one if we look at the game object we can see I've got this physics Cube here so this is the one we exposed here with the serialized field and all I did was I dragged this rigid body onto here so I got a reference to it if I press play now you see that not a lot is going to happen it's just going to stay here suspended in air because gravity is pulling it down but my script every physics update it's applying the force to compensate for the gravity but if I disable this mon behavior I'm actually going to take away the force that I'm pulling up and it's going to start falling down any physics manipulations that you do to a game object if you have a rigid body onto it any physics code if you're moving the rigid body if you're adding Force to it then you should do it in fixed update not in update but it's very important not to read keyboard input in here because you're going to miss them sometimes it'll work and sometimes it won't you will miss some of them in fixed update so don't put keyboard inputs in this fixed update all right let's move on to the next one we've got a mouse Cube here so we've got some more cool monab Behavior stuff here if I double click on this one we can see what have we got here so we're inheriting from mon Behavior very important and here we got void on Mouse enter we've got on Mouse exit and on Mouse down and if you write these in the mono Behavior then if you move your mouse cursor in over a game object that has a collider and the script to it it's actually going to execute we're going to log something to the debug log just saying on Mouse enter and we're going to change the cube color to red when we move the cursor out away from the object then we're going to just debug log it so we know that it happened and we're going to put the material color back to White also if I click on it so on Mouse down then we're going to spit out into the debug lug here that we've clicked on it and we're going to change the color of the object to a random color so let's have a look at what happens we've got this mon behavior that has to be active like this and I move the mouse in over my object and it goes red and we see in the debug log at the bottom there on Mouse entered nothing happens if I just keep moving the cursor around here onto the object but if I move it out then on Mouse exit is called and if I click on it then we randomly change the color because Mouse down was called on it and there are more on Mouse events you can do on drag and all sorts of things so imagine you're making a game where you need to click on objects find hidden objects open close doors maybe you want to have a Crosshair shoot something and try to figure out what you've clicked on you want to pick something up maybe you want to squash some grapes or slice some fruit who knows then these are already just there there for you to uce Mony behavior and then you've got all these on Mouse enter exit down and up and out and in and whatever just make use of those pretty cool stuff all right so let's move on to the next one and we're going to have some visibility stuff here it might coming into a real now that you haven't uh really explored so much with the Mony behaviors and their methods let's have a look at the Mony behavior that we' created and here we've got un beame invisible and un beame visible and this one is going to be called automatically when the game object became invisible to a camera on became visible the opposite when any camera in the scene sees this game object then it's going to be a calling this function here if I press play okay we can test this by let's just manually drag this position of the cube let's slide on the x-axis and then pull it out and let's see here we go we got a log entry here saying that it became invisible to the camera and if I move it back in then it became visible to the camera and invisible and visible and this is very useful sometimes you you want to disable like computation heavy calculations on game objects if they disappear out of screen especially if you got a lot of game objects imagine you have like hundreds or even thousands or something of little characters or something maybe you want to switch off their animations and do whatever you else switch off their audio disable a whole hierarchy of components or something one thing to be a little bit careful or just aware of it anyway we clear this one notice that it actually disappears out of the camera but it's still not called it until I've dragged it out a little bit further and I have to go a little bit and there we go the reason why that happens is because uh we've got like things like Real Time shadow casting and we could have Reflections and different types of things that is affecting so the camera needs to make sure that it's actually out of all those type of ranges too before it's not exactly when it's V invisible to the camera itself it's when it can consider okay I don't have to consider this object anymore let's go to the next one we've got a reset Cube here so what does this one do let's look at the Mony Behavior so here we go reset this one's not used very often but it could be really handy especially if you write stuff for the editor in edit mode I haven't pressed played and I look here I've got this mon Behavior I can click on this one and I do reset then reset was called and the value was zero and if I take away this mod Behavior Al together and I add it again let's clear this log here and we'll do reset and validate drag it in then we can see that reset was called because when you add the component for the first time in the editor mode then it's going to call the reset to it's good to initialize values and things like that for game objects this way we also have a different thing here and I've remed this one out or commented it out if I uncomment this one we've got one called onvalidate that was called and this is also an edior feature that comes with a Mony behavior and we can see that it was already called here bonds and if I change this up value five or six or 654 then this unv validate is called could be useful as well if you want to save stuff to persistently on the fly when you edit stuff the reason why it wasn't enabled by default here is because it's talks a lot if it's enabled it's is going to be doing it quite a lot when you do any manipulation to this one all right so let's move on to some other methods that come with the mon behaviors let's look at the Collision cubes here so we've got a cube up here let's see this is actually a little hierarchy of game objects we've got a cube up here with a rigid body and gravity is applying to it and we've got a monob behavior called monob Behavior collision and on the lower one it's just a static Cube here with a box collider and let's look first at the script so we know what to expect so here we got a little bit more code the first one is we want to just grab a reference I'll do that through the code here instead of doing it like I did before with the inspector so we got declared a rigid body here and we get that component this is also a feature that comes with mon Behavior actually actually through the awake we know that one already runs when the game object is first instantiated into the scene or when you press play and we can actually use this mon Behavior to get component rigid body and then we've got a reference to the rigid body from here on also want to remember the original position and rotation of this object because I want to be able to reset that then we also know what on and enabled us right because when the game object is enabled then I'm going to reset the position and rotation of this object to the original position and rotation so we can test this a few times I'm going to set the velocity of the rigid body to zero and the angular velocity of the rigid body to zero as well so we reset the cube back to where it was and now we come to the mon behaviors that this one was really meant to demonstrate we've got on collision enter and we've got on collision exit and on collision enter actually comes with some useful information here it brings in this class which is Collision class and you can actually get some cool stuff from this one things like you know where the contacts were made you know where in what normal so if you want to add some Sparks or something when you hit something maybe like a bullet or something then you know the the contact normal so you know in which direction you're going to shoot those Sparks and you also got things like relative velocity so you know how strong the impact was and when you do on collision exit then we know that the Collision is finished it's moved away the colliders are no longer contacting with each other I'm also setting the cube to Red here when we got a collision enter and on collision exit we're going to color back to White so let's press play and see what happens we've got objects falling down and it goes red and then white again and we can see that on collision enter was called I got some information here I got the where the Collision point in World space was what the normal direction is straight up so we got XY Z here Y is one so the contact normal was straight I came straight from above here and the reflection Sparks for example would have been upwards here and we know the impact velocity here it was 5. 69 vertically that the relative velocity between these bodies were and since we had things in un enable and undisable then I can just disable and reenable this one because when we run un enable remember I reset the location and the rotation and the velocity so we can just use un enabled on disabled so on collision enter and exit very useful and we also have something similar here and that's on trigger and got a different scene here or a different hierarchy of a couple of Cubes here and this one's named Cube how evil sphere it should be we've got one difference here and if I ex the spear the spear it's not a spear it's a sphere uh this one if you look at the collider I've actually ticked is trigger here h a little subtle thing but when you click it on is trigger it's not actually going to collide like a physical object but it's going to call a trigger function and let's maybe we'll start by pressing play on this one what happens so we've got comes in oh it goes red when it touches that object and it goes white again and see ont trigger enter was called and the trigger object is name is sphere and then we got ont trigger exit what's happening well let's select a cube here and double click on this mon behavior and we see on enable we reset the position here to minus three on a little bit to the left and then in the update we know what that one does it runs every frame and this is where we do our translation code we translate it in the right direction and remember you have to multiply it by time. Delta time otherwise it'll go too fast or too slow and then we've got on trigger enter and we don't get a full Collision here because we don't have any relative velocity or anything like that but we can find out what the other collider was so here we got a reference to the collider which is named other that's how I knew what name it was when we get on trigger enter then it's only called once when you enter the trigger uh change the color to red and on trigger exit here then we know that we've exited this collider and it goes out sometimes a little bit easy to forget that it has to be a trigger so the sphere here remember trigger and another little hidden secret here is that if you don't have a rigid body on this object let's say I take this one away and I press play this one is a bit sneaky because then you notice it's not calling the trigger and this one gets me even to this day a little bit sometimes you actually have to have a rigid body on one of the objects and if you want it to be kinematic you can actually take this one that means that it's going to behave like a not really like a physical Cube It's not going to fall down like with gravity or anything like that it's like a static rigid body just be aware of it that the triggers will only work if you have a rigid body attached to one of the objects let's move on to the last one in this little demo here and we've got messages cubes okay so what do these do we've got two cubes we've got mon behaviors message send and what's this one say I've got another mon Behavior here called mon Behavior message receive all right let's look at the send one first and we have un enable so when it's enabled as mon behavior I'm going to set the position to minus three again a little bit to the left on the update we're going to translate it just like we did before and on trigger enter we're going to have the same as before but here we got something interesting okay other do send message make me red what what does that mean okay it's going to send a message to another monob behavior and execute a function or a method called make me red if there is one and if we look at this receiver one okay let's look at this one this one's called Cube as well should be sphere go in here and double click on this one and here we go un enable Okay it's going to set the color to just white and then here's a function called make me red and when this one is called then it's going to change the color to Red for this and it's going to spit out in the log here that we've make me Red is been executed and you can see this a bit tricky here because it doesn't have any references here it looks like it's not used anywhere and this is a little bit of a quirky thing when it comes to the mon behaviors it's a bit tricky to use the built-in C editor things that just tells you where do I reference this one because this is magically called through this messaging system let's minimize this and press play and we're going to see here now that when this enters here it goes red and it says make me red was executed and then on trigger exit was called but we didn't actually do anything in that code so the key thing here is that you can use this messaging and not only can you send a message to the to a specific game object you can actually send it to parents or ancestors in your hierarchy or to children as well another thing you can do with modern behaviors is invoke either once with a delay or repeatedly or repeating so we had this make me red function here remember and on enable here let's let's do this invoke and then we'll do and we'll have to do a string make me red and then how long should we wait we'll wait one second for this one semicolon there so here when this one is enabled now it's going to invoke make me red but it's going to wait for one second to do it it should go red now before we actually even touch it press play and we go yep it went red because I invoked it another thing we can do here is you can actually invoke it repeating we'll do invoke repeating and then we can have it's going to run first time after 0 seconds and then it's going to run every 0. 5 seconds so invoke repeating is going to run this function called make me red and maybe we should rename this one now to make me any color and we'll randomize here so random. range 0 f to 1f and then we'll copy this one we'll do the same for the red channel for the green Channel and for the blue Channel there here's a little tricky one too because if if you change the name of this method well then this string is not going to work so it's going to be make me any color and the compiler won't complain when that happens so it's a bit tricky sometimes to know if you've uh if you're using this method but now we should have that it's changing the color every half a second to a random color so that's what invoke repeating does there we go it's changing every half a second now and the reason here why this one didn't work is because we had this send message and it says make me red has no receip and it's because we didn't change this string that's the little tricky part that you get here because we changed this to any color any color and the good thing is that the compiler or when you run into it it'll actually throw you the exception so you actually know that something was wrong but it is easy to miss those and if you want to cancel these as well there's something called cancel invoke so you can actually cancel this one out at any point and if you need to cancel an invoke you can actually do cancel invoke and if you do this one it cancels all the invokes or you can actually cancel a particular one one by supplying the string to it as well all right so those are some of the useful methods that you get on the fly when you inherit from money behavior and you can use for your game and it's about 60 or 65 of these predefined message ones and there are other public methods that you can use too and it's really beneficial when you make a game to make use out of these it makes writing the code for the game a lot simpler but there are a few performance implications but most especially beginner developers won't really run into it but if you have thousands of objects and they all run the update method they all do different things very heavily that's called like this all the time where if you're using a lot of these send messages to different object then it could become a little problematic when it comes to Performance for example in line War we can have thousands and thousands of uh different type of units that are moving around you got bullets flying you've got different warheads and explosions going on and it quickly adds up to tens thousands of update methods and sometimes you want to call those manually in a tighter Loop instead of letting Unity do it but for the most part for many many games especially for a lot of indie games you can get away with this it makes it so much easier to develop and it's a real strength and benefit to make use out of these mod behaviors and all the cool stuff that it just comes with if you found this video useful consider giving it a thumbs up and subscribe if you want to learn some more stuff about game development and also a huge thank you to my patrons I couldn't do this one without you and all the demo projects and tutorial projects I do like this I'll stick that on to my tutorial tier on my patreon so that's patreon.com invenia all right until next time have a great one and I'll see you then bye for now
Info
Channel: Imphenzia
Views: 6,514
Rating: undefined out of 5
Keywords:
Id: vqR2_v0Tkck
Channel Id: undefined
Length: 25min 29sec (1529 seconds)
Published: Tue Nov 14 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.