[Unity Coding Tutorial] An Intro To Event Systems - Creating Universal Object Interactions w/ Events

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
object interactions they're in most games and while making games you have probably created many but might have run into the problem that as you make more and more interactions your code gets more and more bloated with subsections dedicated to those objects or have had to repeat complex code for each different object to enable interactions or maybe have wondered how you would interact with multiple objects at once what we need to solve these problems is a middleman script a middleman script is an individual script that a player can find and call a function and then that function can alert any scripts connected to it that the interaction has been made but this has a new problem we need to make an interact script that can function with any other script we make but also doesn't require all of our objects to check for a player interaction every frame and we can do this as you probably have guessed from the title of this video with Event Systems an event system is a way of creating code that rather than having multiple scripts monitoring a change in some value every frame can instead lie dormant until an event is broadcasted that instructs them to run some code so let's create a simple event system for object interactions and to do this let's create a script named something like indirect and then let's open it up once we're inside let's first remove the start and update method since we won't be needing them and the first thing we need to to do is actually create our event system and we can do that by creating a new class at the bottom so let's make a new public class name something like indirect event and the first thing we're going to need is a delegate so let's put in a public delegate with the return type of void named something like interact Handler a delegate is basically a way of storing a list of methods that match the delegate's return type in this case the return type is void so we can assign any method with a return type of void to this delegate we will be using this delegate to store any methods from any other scripts we want to execute whenever our event is triggered and because the methods we call Will usually involve activating some kind of operation like opening a chest for example we can probably stick to our void return type and next we need to create our event so let's put public event that is of type interact Handler and let's name it something like has interacted and now we need a method to call our event so let's put in public void and the same as something like call Interactive end and then let's point this to our event so let's put Lambda has interacted question mark dot invoke this question mark is telling our method to use our event as a nullable value type or in other words it's allowed to be null this lets our event run even if it has no information without throwing a normal reference exception just in case there are no methods subscribe to this event or maybe all the objects that were subscribed to this event have been destroyed for instance now back in our interact class Let's Make an instance of our interactive ends so let's create a new variable of interactive end let's name it interact and let's set it equal to a new interactive end and now this may seem a bit strange but let's also add in whatever script acts as our main player's primary script in this project this is called player so I'm going to add a new reference that is a type of player and we can just call it player next let's create the method that we will call whenever we find this interact script let's put in a public void named call interact and let's also require a player named interactive player this is the reason for the player reference whenever our player interacts with the script they will be required to pass in their primary player script and this will give us the ability to pass along that player reference to the objects that we are interacting with and then inside our method let's just set player equal to interactive player and then to set off our event we just need to put interact.call interactivent and now we need a way for our objects to grab the event in order to subscribe to it and we can do that with a git property function so let's put public interact vent get interactive int and then inside let's put a get return and then let's first check to make sure that our interactive end exists and if it doesn't let's make a new one so let's put if interact equals null and if it does let's hit interact equal to a new interactive end and then let's just return our interactive end let's also do the same for our player so let's make it a public player get player and inside the get function let's return our player now let's set up our player interaction in our player scripts let's make a new public void method called player interact we are going to be firing array out of the center of our camera into the scene to look for an object to interact with and to do that we need a layer mask a layer mask is a binary 32-bit number where each layer is assigned to one of those bits that's why we can only have a maximum of 32 layers each part of this number because it's a binary number can either be one or zero and that represents the true or false for each layer so a layer mask that is all zeros would decline with nothing while a layer mask that is all ones would collide with everything we can easily create a layer mask by using a bit shift operator if we take the number one which looks like this as a layer mask and we use a left bit shift we can move this one along the number by the amount put after the bit shift operator so if we put one bit shift 3 it would move the one over three steps by default Unity uses layers 0 1 2 4 and 5. for some reason so if we were using layer 3 as our ground layer and we wanted our array to only collide with the default layer on layer 0 because our interactables are all on the default layer and the ground layer on layer 3 so our Ray is blocked by the ground layer for example we could make layer masks of those layers by first making a layer mask that is equal to one bit shift zero because we want to collide to the first layer which is layer 0 and then another layer mask that is one bit shift 3 to collide at the ground layer and to combine these layer masks we can make a final layer mask that is equal to our layer mask 0 or our layer Mask 3 and now we have a layer mask for layer 0 and layer 3. now let's set up our raycast let's make a local variable of raycast hit and name it hit and let's make a local variable of Ray named array and let's set Ray equal to camera dot main dot viewport Point array viewport Point array is a function that returns array out of our camera based on the location we choose in the viewport it uses a normalized scale on the X and Y axis meaning that the point in both directions is between 0 and 1. so choosing a location at 0.5 on the X and 0.5 on the Y will be the center of our screen the z-axis is ignored in this function so we will set it to zero and with that setup we can Now cast array so let's put if physics array cast and let's pass in Ray for array and then let's put out to out our information to our hit variable let's set the distance to something like 15. this may be a bit far so you may want to lower this if you're able to interact with stuff a bit too far away and then let's use our final mask for the layer mask by the way because a layer mask is just a binary number represented as an integer it even says this in the physics array cast syntax helper we could also just use the decimal number that equals the binary number because binary is just another word for number system base 2 rather than the decimal number system base 10 that we normally work with for example our layer mask here uses layer 0 and 3 which would be one zero zero one which in binary is the number nine so passing in the number 9 as our layer mask gives the same results and then inside let's look for an interact script let's make a local interact variable and let's call it interact script and let's set it equal to hit.transform.git component interact now we can check if we found anything so let's put if interact script and this will return true if it exists and then we can put interactscript.call interact and if you remember our call interact script requires a player so let's use this to pass in our player script and how to call this method in our update function let's put if input.getkey down key code e or whatever key you would like to use then we can call player interact now that we have an interact strip and a way to use it let's see how we can set up our objects to respond to the event let's say we have a chess script and in this script we have a method we want to call to open and close the chest to call the method we need to subscribe it to our event system first let's create a public interact reference name something like open from interaction now to subscriber method let's use the on enable function and inside let's first check that our open from interaction references in null and if it's not let's put open from interaction.getinteract event dot has interacted plus equals open jest or whatever your method is named for opening your chest now it's important to know that subscribing to events does store some memory so we need to make sure that we are unsubscribing to the event whenever our object is disabled or destroyed so we can avoid a memory leak so let's also use the on disable function and let's repeat this process to subtract our method from the event whenever our object is disabled on disable is also called when an object is destroyed so this will handle both scenarios for us now we can add an interact script to our chest let us directly interact with the chest [Music] or we could even reference an interact script in another object like a button to open the chest for any number of shifts an event system isn't limited to one method per system so we could have one button interact with as many objects as our project to handle there's also one more feature that our interaction has because its two references is either created in the script itself or passed in by the player interacting with the script our interact script has no setup meaning we could add an interact script onto anything we want in code and make that object interactable we just got to subscribe to the event for example let's say we have an item pickup script and we don't want to have to go through every item prefab in our project and add an interact script we could instead add the interact script when the object is created our script has a method to give our player an item but requires a player script to add said item this is where our interact script having a reference to the player that interacted will come in handy let's again make a public interact reference and now let's create a new method to subscribe to our event system that will grab our player reference from the interact script so let's create a new public void named interact pickup and inside let's just call our add item method but for the player let's use our git player property we created earlier now let's again use on enable and let's first check for an interact script on our object so let's make a local interact variable name something like check and let's set it equal to git component interact then let's put if check and if it exists let's set our reference to the one found and then subscriber interact pickup method to the event now if we did not find an interact script let's create one let's put else and inside let's first create a local interact variable named adcomp and let's set it equal to this.gameobject.addcomponent interact and this will add an interact script to our object now we can set our reference to this newly created interact script and subscriber method to the event and then in on disable we can first check that we have a reference and if we do we can unsubscribe from the event and now we have items that will add an interact script automatically and now we have our object interact system I hope this video was helpful and maybe brought some ideas on other cool ways to use Event Systems remember to like comment and subscribe if you liked the video and I'll see you in the next one later
Info
Channel: Joseph Mask
Views: 7,576
Rating: undefined out of 5
Keywords: Draw, Drawing, Sketch, Sketches, Paint, Painting, Digital sketch, Digital painting, Digital Illustration, Illustrate, Time lapse, Digital Drawing, Photoshop, Art, Digital Art, Unity, Unity3D, UnityVFX, VFX, Visual Effect, Blender, Game, Game Dev, Developer, Game Developer, From Software, Shader, Shader Graph, Game Engine, Software, Tutorial, Guide, How to, Rogue-Lite, Items, Item, how to make a game, gamedev, indie game, unity game dev
Id: MdOi9ymb07s
Channel Id: undefined
Length: 9min 20sec (560 seconds)
Published: Tue Apr 25 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.