Learn C# with these 9 LINES OF CODE - Unity Tutorial!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys and welcome back to black thorn prods what if i told you that you can have a very solid foundation in c sharp programming by only mastering nine lines of codes that's right guys in this video i'll share with you the nine lines of code do we use over and over again in our projects that will give you the power to make some amazing games so programming seems like a very daunting skill to learn and i can clearly understand why i mean when you see visuals with all these crazy lines of codes it can scare almost anyone away so the other day i was contemplating on the best way that i can teach people how to get started with coding in c sharp so i opened some scripts on our latest game robo and i quickly came to realize that there was these nine lines of codes that made up a huge part of all the game scripts but first this video is sponsored by xsola it's an awesome intuitive code-free tool that can help you craft the right website for your game you can design anything you need from a simple landing page to a complex community hub you can start with a deaf friendly template from their catalog and customized to match your creation are built entirely from scratch in short it's your game's home on the web a great presentation tool and a store where players can buy your work check out the link in the description where you can register a publisher account and start using the site builder so line number one that we use all the time are of course variables these guys are everywhere and you'll often see them at the top of every script variables are basically like boxes that contain data they store some kind of value inside of them variables are incredibly useful to be able to easily tweak the properties of one of your objects so for example i might have a fireball projectile which can have different variables that i can modify such as the speed of the projectile the damage it gives the particles that it will spot on impact and so on so the way you create a variable in c sharp is very simple first of all you need to specify if your variable should be public or private a private variable is only accessible from within the script that you make it from whereas a public variable is accessible from any script public variables also appear inside of unity inspector which makes it that much easier to tweak the values once you've specified the protection type of your variable you then need to tell what kind of variable you're making so there are string variables which is just text then we've got int variables which is stored for integer so basically whole numbers next we've got float variables which are decimal numbers and then finally we've got both variables which contain either the keyword true or false so those are the four basic types but of course there are also all the component types so for those who didn't know objects in unity are composed of different components or features and we can store those components in variables also so we can make a transform variable or a rigidbody variable and so on and the last step that you need to do in order to create a variable is to name it the naming is completely up to you of course you can then optionally assign a value to your variable and then end the line with a semicolon okay so in this example i've got this little queer character who has a player control script that just lets him move around in the scene at the moment his speed is set to a hard coded value so i can go ahead and create a public float variable called speeds public since we want it to appear inside of the inspector a float because we want to have a nice amount of precision on the value of the speed in case we need to use a decimal number and then i just went ahead and called it speeds i've decided not to assign a value to it in the script since we will be doing that from within the inspector hence why we made it public now that we have created that variable i can now replace the hard coded number with that variable alright so now thanks to our variable we can fine tune the speed of our character directly from within the inspector line number two that we use over and over is get components so remember i told you that objects in unity are made up of components well sometimes we need to retrieve a certain component on an object to then modify it within our script so in this example i've got this little character in my scene who just has three components the default and obligatory transform component that lets us modify the position rotation and skill of our objects this sprite render component that is in charge of rendering the graphics of our character and finally a completely empty c sharp script that i created called change color so that's exactly what i'm going to do i want the script to change the color of my object from its default green color to blue for example so in the script i will first of all create a private sprite renderer variable called renderer so we are making a variable with the same type that has this component right here but we now need to assign it a value and that's where our get component line of codes comes into play inside the start function i will set my renderer variable to be equal to get components then inside of these brackets we need to specify what component do we want so sprite renderer then finish with a pair of parentheses and a semicolon so with this line we're simply storing inside of our renderer variable the sprite renderer component that is attached to our character and now we can modify tour liking that components so in this scenario i will say renderer.color and set it equal to color.blue so now when i press play you'll see that your green character turns blue note that this get component line only allows us to retrieve a component on the same object that your script is attached to okay line at number three is instantiate this super useful line lets us spawn game objects from within our scripts the syntax is very simple we just need to type instant shades and then we need to give it three different parameters inside of the parentheses the first one is the game object do we want to spawn the second is the position at which we want to spawn it at and the third is the rotation do we want to give it of course end the line with a semicolon okay so in this little example i've got a completely empty scene except for this empty game object that just has a script attached to it called instantiate example in the script we will first start off by creating a public variable of type game objects called character to spawn like that we can now drag and drop our character prefab inside of that variable slot so that unity knows what we want to spawn with that done we can now use our instantiate line and pass in our character to spawn variable for the object to spawn that way our script will spawn whatever game object that we dragged and dropped inside of our variable slots next for the position at which we want to spawn him at we will type vector 3.0 which will just instantiate him in the middle of our screen and finally for the rotation i'll say quaternion dot identity which means no rotation all right with that done you'll see that when i press play our character gets spawned in the scene this line is used so often i mean whenever a game spawns in bullets particle effects waves of enemies and so on you can be pretty sure that this line of code is behind it all okay passing on to line 4 which is the opposite of instantiate and that's of course destroy so the syntax for this line is also very straightforward you just need to type destroy and then inside of the parentheses specify what game objects you wish to destroy you can optionally assign a second parameter to this line of codes which would be a float that dictates after how long would you like to destroy the objects of course and the line with a semicolon okay so in this example we've got in our scene this character and their job is to destroy it we've also got a destroy example script attached to the character let's start off by creating a public field variable called lifetime then inside of the start function we'll use our destroy line of codes as i mentioned we now need to specify what game object do we wish to destroy in our case it's this object the one that has this script attached to it so we can just type game objects then for the second parameter we'll pass in our lifetime variable this way our object will get destroyed after our lifetime has passed so in unity i'll set my lifetime variable to 2.5 and indeed once 2.5 seconds have passed you will see that her character gets destroyed so instantiate and destroy i really like the bread and butter of game programming i mean think of any game and you'll quickly realize that there are always new things getting spawned on the screen and other stuff that goes away next off we've got piece of code number five which are loops in this video we'll just go over the most common for loop but there are also other types of loops that exist so a loop is basically a way of repeating a certain piece of codes the syntax is the following first we start with the keyword for then we put a pair of parentheses inside of those parentheses we start off by creating an integer variable which is often called i by convention which stands for iteration then we just assign it to the value zero you could of course set this variable to whatever you want but i'm just showing you what is most common then just finish this section with a semicolon this is the initializer next we've got the condition so this could be something like i smaller than three and then end it with a semicolon so basically the loop will continue to run as long as this condition is true so as long as i is smaller than three and finally the third part is what happens to the variable i each time the loop runs so this could be something like i plus plus which just means add one to i each time we go through the loop okay so to recap we first of all initialize an integer variable and set it equal to some value then we state a condition and the loop will continue to run as long as that condition is true and finally we need to say what happens to the variable i each time we go through the loop so here we often increase by 1 the variable i so pause the video now and try to think about how many times this loop will run and the answer is three times so at the start i is equal to zero we are then checking if i is less than three so of course zero is less than 3 and so we'll run whatever chord is inside the loop and then we'll add 1 to i so now i is equal to 1 we're then repeating this process so is i still less than 3 yes until you run the loop again now i is equal to two which is still less than three and so it ranks again and now we come to the end since we add one again to a variable i which is now equal to three and since three is not less than three well then the loop stops running okay so in this little example i've got an empty scene with just this one game object who has a script attached to it called loops example so i would like to spawn in using a loop a bunch of trees i'll start off by creating a public integer variable called number of trees to spawn so if we set this variable to 10 then we'll want to spawn 10 trees if it's set to 30 then we'll want to spawn in 30 trees let's then also create a public game object variable called object spawn that you guessed it will store our tree prefab so inside of the start function we need to create our loop if you've already forgotten the syntax to do so that's not a problem if you just type the keyword for and then press tab twice it will also complete it for you we'll have our variable i start at zero and then we will continue to run this loop as long as i is less than our number of trees to spawn variable and then each time we go through the loop we'll increment our variable i by one now inside the loop we'll use our most used line of code number three which is of course instantiates to actually spawn in a tree so don't pay too much attention to this line of codes here but we're basically calculating a random position so that trees spawn a little bit randomly across our game worlds so each time we go through the loop we'll instantiate whatever game object we dragon dropped inside of our object to spawn variable he'll get spawned at a random position variable that we just calculated here and with no rotation so quaternion dot identity so now if you press play you'll see that our little cute trees are getting spawned across our game thanks to our loop let's now move on with piece of cold number six which are if else blocks this is a huge one these guys let us code decision inside of our game which means that with one c sharp script there can be different outcomes let me give you a few examples of scenarios where you might need to use conditionals let's say that you want to open a secret door if the player finds a special key or let's say you want to play an epic music when the boss is almost dead well these would be perfect examples where you'll need to use and if else statements so this is the syntax you type the keyword if and then inside of the parentheses you put a condition and then in between curly brackets you put all the code that you want to run if that condition is true if the condition isn't true nothing will happen optionally you can add a nail statement right after your if statements all the code in between these curly brackets will run if the condition isn't true alright so in this small example i want to have a bool variable so a variable that contains either true or false called something like is girl if that variable is true then i want to spawn in a female character and if it's false then i want to spawn in a male character so in my scene i've just got a game object with an empty c-sharp script attached to it called male or female now inside the script i'll make two public game object variables one they'll store our female character and the other they'll store our male character let's also go ahead and create a public bull variable called is female i'll check if my is female variable is equal to true note that to compare if two values are the same in c sharp we use the double equal sign if that's the case then i'll go ahead and instantiate the female character in the middle of my scene and with no rotation elsa so if is female is false then we'll go ahead and spawn in the male character instead okay so back in unity i'll drag and drop my female character into the female slot and the male character into the male slots let's start off by setting is female to true and yes right enough the female character is getting spawned and not the male but if we now set is female to false you'll see that the opposite happens let's now tackle line number seven which is input dot get access raw so games are an interactive piece of art and so at some point in time you'll need to manage some kind of input from the player in this video we'll focus on keyboard inputs but there is of course mouse input control inputs and so on so inputs don't input.getaxis raw horizontal will basically return one if you're pressing down on the right arrow key negative one if you're pressing on the left arrow key and zero if you aren't pressing any likewise input dot get access raw vertical will return 1 if you're hitting the up arrow key negative 1 if you're pressing down on the bottom arrow key and 0 if you aren't pressing any these two lines are used very often when creating player movements so i've opened back up my very first example scene that was for variables which is just this little character that can move around the scene thanks to his prayer control scripts that we made and now if i open that script you'll see that the two lines that we just talked about are indeed in this player controller so let me quickly go over it so inside of the update function we are creating a vector3 variable called player inputs for those who don't know a vector 3 is just a variable that contains three different values an x value a y value and a z value we're then setting the x value to our input dot get axis raw horizontal our y value to input the g axis row vertical and our z value to 0 since this is in a 2d space so if we aren't pressing any button this variable will be equal to 0 zero zero if we're pressing on the up and right arrow keys the variable will be equal to one one zero if we're only pressing the bottom arrow key it will be equal to zero negative one zero and so on i think you get a grasp of it then we're just setting our character's transform position to be equal to his current position plus our move input vector 3 that has been normalized which just means that it ensures that your character doesn't move faster when going diagonally as opposed to going in one single direction we're then multiplying our input variable with our speed variable so we can tweak how fast he can move and finally we need to multiply also with time delta time to make the game frame rate independent this just means that the player character will run half fast on a old laggy computer or in a new fast pc so as you can see this line is vital to be able to retrieve player inputs and then be able to move his character in the direction that he wants you're also able to get a little deep dive into how to make a very simple player control script moving on with line number eight which is vector two dot move towards we use this line a ton it's the black dome prod speciality this line does exactly what it says it moves an object from a point a to a point b with a certain speed so you can basically just sense the transform dot position of the object you want to move to vector two that move towards this line takes three different arguments the first one is the starting position so that's most of the time just the current position of your object so transform.position the second argument is the position you would like to move towards so the target position and finally the last argument is the speed at which you would like to go from the starting position to the target position all right so let's open back up our example scene with the character that can move around we've went ahead and added an evil enemy that has an empty c-sharp script called chase so that's exactly what we want him to do we want him to follow the player around so in this script i'll start off by creating a public game object variable called targets this variable will of course store our player character since he is the enemy's targets so let's drag and drop him inside of the slots then i'll also create a public float variable called speeds so we can control the speed of our enemy the inside of the update function is where we will use our special line so i'll set transform.position to be equal to vector2.move towards we'll go from our current position so transform dot position to the target's transform.position and then i'll pass in my speed variable of course i'll not forget to multiply it with time.deltatime to make the movement frame rate independent like we briefly discussed before and look at the amazing results that we got with so little calls the enemy is perfectly following the player rounds with just one line of code and finally the ninth piece of code that we use everywhere is the on trigger enter to the function basically whatever code we put inside of this function will run automatically when your object collides or touches another object so you simply need to write void on trigger enter 2d and inside of a pair of parentheses you need to take in as an argument a collider 2d called other so this other argument will basically store the collider to the components of the objects that we collided with so in unity in order for a collision between two objects to be detected we need a couple of things first of all both objects need to have a collision on them you can think of a collector has an invisible aura around your character to just let unity know about the boundaries of your character so let's go ahead and add a box collider to the component to our prayer character you can then go ahead and click on this button here to tweak the size of the clutter so that it best fits the shape of the player we will then go ahead and check the is trigger box here so we can detect collisions with this object from within our scripts we will then repeat this exact process and add the box coder to the component to our enemy so now that our two objects have colliders we need at least one of them to have a rigid body 2d components rigid bodies are basically components that allow a game object to react to real-time physics so i'll give a rigid body 2d component to a player for example we'll just go ahead and set the body type to kinematic so that our object doesn't get affected by gravity okay so to quickly recap in order to be able to detect a collision in unity we need both objects to have a collider on them set to trigger and at least one object needs to have a rigid body component we're also going to select your enemy and we're going to give him a tank so tanks are used to just basically identify an object you'll see what i mean by that in just a couple of moments but for now just go ahead and create a new tank called enemy and then once that's done assign that tank to the enemy character we'll now open the player control script so let's go ahead and create our void on trigger enter to the function now inside this function we will check with an if statement if other dot tag equals equals enemy so we are basically checking if what we hit has the tank enemy on it if it does then we'll go ahead and instantiate some blood particles to let the player know that he got damaged so i'll come up here and create a public geometric variable called particle effects then back down here i'll instantiate our particle effect at our player's current position so transform dot position and with no rotation so quaternion dot identity all right so back in unity i just need to drag and drop my effects into the slots you'll now see that when the enemy touches the player some juicy little particle effects get spawns and that's it guys we have finished covering our nine most used piece of chords to create games i mean it does if you master these nine lines of codes you'll be in a great position to start creating some awesome games just take a look at our largest example scene we have a player that can move around with the arrow keys an enemy ai chases the player around and it damages him if he gets touched and we were able to create all that with some variables some if else statements some input.gex is raw a little on trigger enter 2d and of course the sneakyvector2.move towards so i encourage you to mix and match these awesome pieces of chords and try to come up with some original little games if you got some value out of this video please hit the like button down below to let us know that you like this type of content so we can keep producing it for you also comment down below what line of codes you like the most anyways thanks for watching cheers [Music] you
Info
Channel: Blackthornprod
Views: 46,509
Rating: undefined out of 5
Keywords: blackthornprod, unity, tutorial, c#, programming, art, game dev, coding, how to code, coding games, C# for beginners, Learn C# with these 9 LINES OF CODE - Unity Tutorial!, C# programming, c# and unity, coding in unity, programming in unity, programming basics, coding for beginners, easy, variables, loops, if statements, instantiate, destroy, get component, collisions
Id: aB9LJ9oHGOs
Channel Id: undefined
Length: 25min 15sec (1515 seconds)
Published: Fri Jun 18 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.