How to Use Dictionaries in Unity and C# [BEGINNER FRIENDLY]

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] oh sorry about that i was just reading my dictionary you might be surprised to learn that using a dictionary in c sharp and immunity isn't too different from using a dictionary in real life let's hop right in and i'll show you what i'm talking about okay so it goes without saying that using a dictionary in c sharp in unity can be a little more complicated than using a dictionary in real life and that's why first and foremost the goal of this video is to help you understand exactly what a dictionary is in here and do it in a way that's easy for you to understand as a beginner next we want to help you understand when you should use a dictionary they can be tremendously powerful tools especially if you're using and implementing them correctly they can save you a ton of work down the line so i suggest that you really try to get familiar with them as fast as you can and then speaking of which we're going to show you how you actually go in code and write a dictionary use getters and setters and use them to set definitions and retrieve values that you want but getting started what is a c sharp dictionary exactly and this most simple way of explaining it is it's a useful tool for receiving specific information and it works by being given a key and then it returns a value for you but what exactly does this mean even that doesn't sound too beginner friendly well let's look back at this real dictionary as an example so in a real dictionary you know the word that you want the definition for and you have to look up its definition so let's say for example that i'm playing scrabble and i make the word quaff for a ton of points on the triple word score and my opponent goes you're a cheater what what the hell is quaff well i know that i want the definition for a quaff but if i just wanted if i just randomly hope to find it in here it'd be really hard if i didn't know the word quaff but because i know the word quaff i can go to this page here where i bookmarked it and find out that quoth means to drink heartily or in one drought so the word here is my key and the definition is the value that i'm trying to retrieve and just like i've said it here and i'm using the colors to keep it straight for you the word is the key and the definition is the value and this is how a unity dictionary works as well in c sharp or in unity you make a dictionary and then give it the word or the key that you want to look up in this case quaff and then you retrieve its definition or value but this would be considered a string and a string i'm looking up quaff that's a string and i'm returning the definition of cough which is also a string in unity you don't have to be restricted to strings both your key and your value can be any type of variable so you can use an integer for instance uh to look up a boolean value so it was number 20 is value is key 26 set to true or is key 26 set to false this is the power of a dictionary now let's take a look at a real game here that's using dictionaries in it this is called portal galaxy it's a game that i made for android go download it that's my bit of self promotion here and like many android games it is using an objective based system as players progress through levels they have to meet certain criteria and when they meet that criteria they earn a star now a really inefficient way of coding this would be having a single bool for each level and for each star but by using dictionaries we can trim all of that down to only using a handful of very small dictionaries that manage all the levels now let me show you what i mean by that in the back end okay this isn't the actual script that i use in the game but i want to show you what this process might look like if we weren't using dictionaries and then show you how much better it looks because we are in this case so in the first instance if we weren't using dictionaries and we were using individual bulls we would have to have multiple bulls for each level so the first level would need three bulls called level one first star earned level one second star earned level one third star earned and then the same thing for level two the same thing for level three and so forth you can probably see that would be a ton of work and you can can tell just by looking at that it would be really really inefficient and a bad idea now you could slightly trim down on that by using a raise instead and now instead of having three bulls per level you could only have one bull per level for all the stars uh which just is an array and instead now we have level one stars earned and make it size three and the same for level two and three the best way is to use dictionaries now in portal galaxy's case what i did is i have three dictionaries uh one for handling each star one for the first star earned one for the second star earned one for the third star earned now at the time i was coding this game i didn't realize that there was an even better way of doing it which is that you can put an entire class into a dictionary so instead of even needing to have three dictionaries i could just have one dictionary to manage all of the levels in the entire game and then through this single dictionary we could retrieve all the values on an as needed basis so if i was to go here and to start and declare level level is equal to my level dictionary at position one i can now type level and go into this and get the functions out of here that are public and accessible like level dot first condition okay so i hope you're starting to get a good sense of why you might want to use a dictionary but what about the when when is it the right time to use a dictionary over say an array or a list which admittedly are kind of similar well the first time you might want to use a dictionary is when there are a lot of very similar variables that might otherwise be required but even this isn't too distinguishable from an array or a list at this point any three of them might be a good option but a dictionary comes in handy when you need new key value pairs to be as signed and retrieved on the go now with my game portal galaxy for example as i've mentioned i use dictionaries extensively when i'm creating levels now the advantage here is that as i create new levels all i have to do in the front end is copy and paste a new level and then i just have to in the inspector view change things like it's level id and some of the criteria and objectives associated with that level that the player must meet but no coding is needed in the back end that's all done and that's all handled through dictionaries dictionaries make this process really really easy and finally when you want to retrieve specific information about a particular object dictionaries are a great example because you're giving it that key and you're retrieving that value so i'm doing this all the time in portal galaxy in the other games i'm working on but think about a game like an rpg where you're creating a sword or a shield or a bow or a spell and each one of these objects has different stats associated with it weapon damage defense magical power all of these values can easily be handled and retrieved by a dictionary as they're needed without taking any additional operating power from the user's device whether that's a smartphone or a computer so i realized that my game might be a little bit complicated in terms of understanding how dictionaries work so what i've done here is i've created a very simple example and we're going to follow along exactly with the code and i'm going to show you how to code your own dictionaries so you can get started right away now in this example all i'm doing here is i'm entering a level number and i'm going to say level 2 for example and saying get values and it's gonna tell me whether or not stars have been earned i type level three press get values and it tells me the values for that level four five and i can just keep doing this over and over let's go into the back end and take a look at what's being done so here is the back end for this game now this isn't really a game it's just an example so the level script has only four variables in it that are declared this public integer level id represents our dictionaries key and then we have three private rules which are serialized so we can edit them in the inspector to determine if the stars have been earned for each of these levels now if we go back up here into the game view we can see by clicking on each of these levels that we have manually edited the level id in each of these levels to be representing level one two three four and five and then just setting some values for whether or not the first second or third star has been earned in a real game first the stars being earned would be determined by the player but for this example we're just setting that manually let's go back to the script the very first step is to add levels into the dictionary and we do that through in the level script which is attached to each one of these levels in the start method just typing the method name add new level in this add new level method we're sending our key and values to the dictionary and the dictionary is declared in the level manager script now again the key is the level id and our value is this script itself we're starting off by finding the level manager through gameobject.find object of type and if this particular line of code confuses you i have another video i'll link which explains this in great detail and then in the level manager script we're calling the method add new level and passing through our key and our value now in the level manager script this is how we declare a dictionary first we set it to either be private or public then we call it a dictionary we declare the key type we declare the value type we give it a name and then we have to say it's equal to a new dictionary and just repeat this information now let's go down to the method here add new level and it's very simple it's one line of code we're just saying level dictionary.add and then adding our level id and the level script or the level class itself into the dictionary now doing it this way is quite simple however it does have potential to cause errors and i'll show you what i mean if we go back up here to the game we are already seeing that if we enter 1 it gives us values 2 it gives us values but we only have 5 levels and what happens if we try to get values for level 6 which does not exist if we press get values it's going to give us a key not found exception and that's because of the way we've currently coded this which i'll be showing you how to fix momentarily but for now i want to finish taking you through the code when we click the get values button we're calling this method here in level manager called set star texts and this is where we're now reaching into the dictionary and we are pulling out the values that we have requested and here's where we're doing this we're declaring a new level and we're calling this variable this level and we're just saying it's equal to our level dictionary at position level id now the level id is taken from this string variable and that's whatever the player has entered into that text box that's converted to an end and then we're using that as our key to reach into the into the dictionary at that position and return this level then we're just using a for loop to go in and use that value we've retrieved to get the star text values basically whether or not a star has been earned at each of these positions that's not the important part of this video i just want to show you how to go in and reach into the dictionary and set those values next i want to show you how to properly add and retrieve values from dictionaries without getting errors now i did just show you how we can accidentally get an error from trying to retrieve a value that doesn't exist but what about getting an error from adding values into the dictionary so all i've done here is i've created a button called add levels and in our level manager script that calls a method called find and add levels and previously where we had been automatically entering these level values from the start method we're just now adding these values manually so let's run it and see what happens if we press this so i press the button once and nothing happens because i just added all of the levels but if i press it a second time it's going to give me this error argument exception and item with the cm key has already been added and that's because we're trying to now double enter these levels into our dictionary and it's telling us hey what are you doing these values already exist you can't enter them twice let's see how we can go and fix that so this right here is our problem line we're trying to add the values and the first time this works okay but the second time it's giving us that error instead of just typing this line of code we can contain this within an if statement and what we want to do is say if level dick dot contains key for saying if this key already exists and the key being our level id instead of adding it what we want to do is just update the dictionary so key already exists don't add update now we're going to say level dick at position level id equals this level so this we're just basically accessing it the same way we would in an array and we're just giving it a new value now under else we can say this add the new level just cut and paste that in there save and let's go test it out actually first just to be thorough we'll put in print statements and say level already exists updating and here we can say print new level added now if we hit play we can say add levels and it's going to tell us new level added and it's going to do this five times because there's five levels and if we do it again it's going to tell us level already exists updating and if i press it it's just going to run that five more times and now we can add or update levels without encountering errors now finally what about getting levels without getting errors well instead of it's very similar actually but instead of calling this we're going to write a new method here and we're going to say get level from dick and now we're going to write this method here and we're going to call it private level get level from dick and now we're going to write out level level equals null for now and then we're going to return the level at the end and now we're going to reach into that dictionary and see if it exists and how are we going to do that well again we're going to basically write the same if statement if level dick dot contains key and actually i forgot to pass through the key so we're going to do that first so under here we're going to pass through our level id and then we're going to declare int level id and now we're going to ask it if this dictionary has that level id in it and if it does have that level id we can say level is equal to what we copy pasted earlier level dictionary at position level id and then we can write an all statement and we can just debug dot log this by saying trying to get level value for a level that doesn't exist and now we could return level which is either going to return as null or it's going to return as the requested level and there's one final step we can say if this level equals null return now we can do something else here perhaps a little more interesting but for now this should suit our purposes so let's try to run this and see what happens so we're gonna run the game and we know already that first we're gonna add the levels because we have to add them manually and now if we try to get values for level one it's going to give us that two it's going to give us but if we type in level six it's it's not going to give them us our values however it's also not going to give us an error it's just going to tell us we're trying to get level values for a level that doesn't exist we can get them for five though but six not gonna exist seven not gonna exist or pretty much anything else and this is a much safer way of coding dictionaries because we're just accounting for some user error or even some errors that we might accidentally throw at the game hey so i know dictionaries can be a bit of a tricky subject to get a grasp on but i hope that by watching this simple video even with these really basic examples that i've been using you can already start to see the tremendous power that dictionaries have and how they can really help you streamline and keep your game organized so you can take it to the next level please feel free to let me know if you have any questions or comments and in the meantime i'll see you in the next one you
Info
Channel: Unity Game Programming For Beginners
Views: 8,196
Rating: undefined out of 5
Keywords: Unity, C#, tutorials, game dev, Game programming, unity game programming, unity game development, game programming for beginners, how to make games, unity game programming for beginners, help making games, help with visual studio, visual studio, code in c#, dictionaries, C# dictionaries, Unity dictionaries, how to code dictionaries, how to use dictionaries, game development
Id: Cyj60xwhvb8
Channel Id: undefined
Length: 18min 58sec (1138 seconds)
Published: Mon Jan 25 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.