Want to Start Writing Code in Unity? Start Here! Unity C# Basics Part 1 - Writing Your First Script

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey chris here from mom academy here to help you yes you make your game dab dreams become a reality in this video we're going to do something totally different than we've normally been doing i always have been assuming that if you're watching one of these videos you kind of already understand how to write some code but that leaves out a lot of you who maybe are copy pasting to get some results and don't really understand what's happening underneath with all that code that we're writing in each tutorial what that means is this is part one of a new series where i'm going to focus on very basic introduction to coding type of things that you need to know to get started writing your first scripts and get into your programming journey in unity using c sharp in this one we're going to write a really basic script that we've kind of done something really similar actually my very first video but what we're going to do in this one is slow it down explain step by step what does this do why do we need this how does this work and where can you go to get help when you don't understand something that's the number one thing i want you to take away from this video is how to help yourself when you don't know what's happening both unity and microsoft give really good in-depth explanations of how to do almost any not everything but a lot of stuff using c sharp and unity sometimes microsoft's documentation can be really technical if you get into like the language specification and if you have the coding background which i assume if you're watching this video in the series you're not going to have that and that's okay you don't need to understand the full depths of what defines a programming language and how does it work in the compiler level that for the most part doesn't matter when you're writing code microsoft does have some pretty good tutorials and pretty good documentation when you're wanting to know a specific thing or how something works in the description we have a bunch of links to all the stuff that we're going to look at and all the references that you're going to need to understand in depth everything that we're talking about in this video also be bringing up while we're talking about each topic some documentation explaining how do i know that we want to use n2 for a number format if you've never written any code before this video is totally safe for you to get started and this is the one i think you should be watching first if you have never written code because we're going to really just break it down like you're writing your very first script even if you don't know what a script is that's okay we're going to talk about it in this video and by the end of this i'm going to assign you some homework so that way you can further your understanding on what we've talked about so far i've got to give a huge shout out to my patreon supporters every single one of you helps the channel grow reach more people and add value to more people and that means more people are making their game development dreams become a reality if you want to become a supporter you can go to patreon.com academy get your name up here on the screen and get a voice shout out starting at the silver tier and speaking of those silver tier supporters i have raphael andrew bowen gerald anderson and autumn k i am so grateful for all of your support thank you to get started let's make sure that we have all the right tools installed first we'll open up the unity hub as a very recently unity hub 3.0.0 is the default one that you'll get whenever you install the unity hub we're going to go to installs on the left side and then click install editor and we're going to choose the latest lts release currently that's 2020.3.26 f1 we want to use the lts release because this is the most up-to-date stable release that unity has the other ones that are available are in the tech stream these contain some features that are not fully production ready or more experimental when we're just getting started we want everything to be stable we don't want to run into some weird bugs so that's why i would always recommend starting with the lts release unless you have a really good reason to use the text stream so i'll click that and we're going to make sure that visual studio is going to be installed i don't want to get too much into the how to set up a unity project i just want to really highlight that we do need visual studio to be installed and this is how you can do it using the unity hub i'll then quickly create a new project based on the 3d template for the scope of this tutorial which one you choose doesn't really matter you can even use an existing project that you already have in our scene i have a text mesh pro ui component on a canvas a background image that is the entire size of the canvas and what we're going to do is make something happen over time that's basically what scripting does is we want to take some values and modify them over some time or whenever an event happens like a user click contact with physics whenever ai has achieved a goal something like that for what we're going to do we're going to just count up with this text over time to start writing code what we have to do is create what's called a script in unity we use the c sharp programming language to write these scripts and all this does is provide us a way to manipulate something that's happening with our game objects our text mesh pro our canvas whatever it is that we want to modify so right click in the project panel go to create c-sharp script whenever we're giving a script a name we want it to be descriptive for what it's going to do that way later whenever we have a lot of these in our complex game it's very evident from just the name what the purpose of that script is for this since we wanted to count up some text mesh pro text i'm going to call it count up then if we double click on that it should automatically open our visual studio if it doesn't we can go to edit preferences we'll get a window that has preferences and click on external tools for the external script editor we click on visual studio 2019 when we open up visual studio and get our count up script open there's some code already here that unity gives us by default at the top we have some using statements that give us access to other code that unity gives us by default and also the system.collections and the system.collections.generic you'll see those two are kind of grayed out because they're not being used so far the unity engine one though is that's why it's the full kind of white text since these are just giving us access to other code and we are using the unity engine and we know in this script we want to use text mesh pro right we're going to update some text mesh pro text over time so what we'll do is say we're going to use text mesh pro that's using tm pro that will then give us access to stuff like the text mesh pro component that we get in the unity inspector that maybe you're already familiar with if we move down a little bit we have a public class count up that's the name of the script that we just did and a little colon monobehavior this line will almost never change for you what unity gives us on this most of the time is exactly what you want having that mono behavior piece is really important so that we can add this component to a game object in the inspector if we remove that we will not be able to add our script to a game object it's also very very important that count up matches our file name so the file name of count up even the case is important should be the same text as our file name exactly if you maybe renamed the file or something like that these can get out of sync the easiest way to fix that is just delete your file and create a new one the curly brackets the way you can think about them is signifying ownership of the code inside so we have curly brackets that come after the count up that's on line six here and the closing bracket is on line 18. everything in between those we're saying belongs to the count up class inside of here at the count up class level we can define functions i may call them methods method function exact same thing i don't know why there's two words for it but there are so function method both of those are the same thing that's what we already have defined here with this void start and then the little parentheses and void update with the parentheses and then those also have curly brackets that come next so what that's saying is there's a function called start the void means that it doesn't return anything and we'll get into what returning does in a future video and then unity says you can put some code here into the start function i'm saying you can put it into because we're going to put it inside those curly brackets these two functions are what i'm going to call magic unity functions unity will call these automatically for you at some point in the game's life cycle in a future video i'll go over that component life cycle but the important thing they already told us here that start is called before the first frame an update is called once per frame which is perfect in most game engines probably all game engines work the same way they will render or display one at a time a bunch of images and over time something small will happen there'll be incremental changes in between each of these pictures and that's how we get the smooth look that's where the 60 frames per second you may have heard of comes from if we're talking about 60 frames per second that means 60 individual still images are shown on the screen every second in this code case you'll see that update is called once per frame so that means this function would be called 60 times in one second we're going to use that information in this video specifically to get that counting up before i get too deep into the functions let's define what i'm going to call class member variables that may sound a little bit scary but we're going to walk through it really slow and we actually need two of these for the example we're gonna do today we're gonna define these two and then we're gonna walk through what's happening okay we go private text mesh pro u g u i and we're gonna call it text and we have to put a semicolon at the end we're also going to define a private float speed and we're going to do equals one and then put a semicolon so what's happening here we've defined two class member variables so remember count up is a class that's why we're calling it a class member we're in the count up class right now we're in between the open and the closed curly brackets for our count up class they are defined at the class level they're not inside of a function they're only defined in the class which means we can use them later in functions and we're going to we're defining two variables text and speed and variables much like the name sounds like are pieces of data that we will most likely change their value over time so their value may vary variable over time a variable has to have a type in c sharp in most programming languages they have to have a type in c sharp there are a bunch of types and you can even see here that we have text mesh pro ugui is a little bit different than the float right it's this green color and the float is blue text mesh pro ugi also starts with a capital letter much like our count up which tells us that text mesh pro ugui is a class or a struct that means it may also have class member variables and functions since i've used this text mesh pro ugi many times before i can tell you it does have class member variables and functions that we're going to use in this video float on the other hand is what we call a primitive type it's not going to have class member variables or generally functions on it because it is a primitive type and what primitive types do is just store some value in this particular case we want to store a number that can have a decimal in it so i'm going to use float you can think of primitive types as just data storage and classes as more complex combinations of primitive types and functions now there are some primitive type functions but they're pretty few and far between so float is a number but there's not just like a number type we have to be very specific about what kind of number we want to be for the most part float is the value you want when you're dealing with decimal numbers if you want to be a whole number it's called an integer or int int in this case the speed is going to be used to adjust how quickly we're gonna count up but if we can only go from zero one two three four that's like a really big step up right that's why we're using a float here so we can have like 0.25 speed so 25 speed or 50 speed so we can go up at a much more granular speed we can kind of ramp it up or ramp it down the other really important type for us to talk about here is string a string type is a text type so if you want some kind of text like if you want something to say hello or by default the text mesh pro component says new text that new text piece of text is a string that is stored in a variable we're going to override that to be some number instead but to display text it needs to be a string so that's why it's important to know that this is also a type that we're going to use in this video variables have types they also have a name in this case the text mesh pro one we called text and the float one we called speed there's a convention that i follow just to make it a little bit more clear to me what kind of variables i'm using at a particular moment where the class member variables i will define starting with an uppercase and the variables i define inside a function i will use lowercase that's a convention you can choose to use as well to keep it more straight in your head about where is this value coming from there's one other thing as part of our definition of this variable though and that is they both are called private you may think about how we have the class defined as public and these are now private you're catching on to something there that these are called access modifiers every class member variable every class and every function has an access modifier there are four key access modifiers that i use there are a couple more but i've never used them so i don't know how valuable those are but there's only two we need to care about in this video public and private public as you may have guessed is open to the world everybody can see what's public and then there's private which you hope nobody can see and c-sharp will enforce that nobody else can see them only in the scope of this class can you see these private variables or private functions generally speaking we want to keep all of our variables and all of our functions at the most restricted access level possible this helps us reduce bugs by not letting just anybody change values of variables from anywhere you end up with a really bad code design when you go that way so that's why the private should be the default access level that you set any variable or function to unless you really know why it should be more accessible than that so for the scope of this one we want them to be private because only this class will modify these values in a future video we'll get into what are some of these other access modifiers and what are those useful for but not to muddy the waters of this video that's the key things you need to know i'm going to do one more thing to these two variables since these are class member variables and they're private there's no way for me to modify them right but in unity i will probably want to modify for example the speed in the inspector how can i do this i'm going to add a square bracket serialize field close square bracket to both the text mesh pro text and the float speed variables this is what c sharp calls an attribute and this one specifically comes from unity that allows them to show private variables in the inspector this allows us to keep our code clean keeping them private while still being able to modify them in the inspector that's a really cool trick that unity has we're going to do one more variable definition here i'm going to make a private because it's a class member variable and i don't want anybody else to modify this besides this class going to be a float because it's going to be a decimal number i'm going to call it time display this is going to be the value that we're going to display on the text mesh pro text and i'm going to assign a value with equals 0 and then semicolon we're going to use that in the update function we need it to be defined at the class member variable level because we want it to stay there outside of the scope of the function in a function we can define time display but it will be reset to whatever we assign it to at the beginning every time the function is called so if we want a number to count up it doesn't make a lot of sense for it to get assigned at the beginning of that function every time because it will always be set to that default value defining at this class level allows us to have it defined to one value and then persist between calls to update we're going to go inside that update function and we're going to write our first let's call it logic lines of code so far we've only done variable definitions but now we want to actually modify those values of those variables over time we're going to introduce a new concept here called the if statement this is one of the most common statements in all of programming it allows us to check if a value is true we do that by typing if then doing parentheses and then what we would like to check what i'd like to check here is that the speed is greater than zero so remember speed is a float value it could be any number negative positive decimal anything like that but since this script is called count up if speed is negative you'd actually be counting down so i want count up to only count up so that means the speed has to be greater than zero that means any value that is positive so we're going to do that and for if statements they act very much like what we saw here on the function where we want to put these curly brackets because we want to put code inside of the if statement that means only if speed is greater than zero do we want to execute this code if the speed is less than zero we don't want to do anything at all inside of here then we want to do something right what we want to do is update our time display because it's going to be the value we're going to display and we're going to change that over time that's going to give us a cool counting up animation on the text what i'm going to do is time display and then i want to change this value right so that means i'm going to do equals because i want to assign a value to the time display and i'm going to put time display again because i want it to equal the value it's currently at plus some other value so we're going to do time display equals time display and we're going to add something so we'll do plus and here we're going to use time with a capital t dot delta time time with a capital t comes from unity engine that gives you information about time stuff the important thing here and what is the most common thing to get from this time class is the delta time the delta time is the amount of time that's passed since the last frame was rendered so remember that in game engines we show a frame we show a frame we show a frame what this delta time captures is the time since the last frame was displayed that's a really helpful thing because update is called once per frame right this allows us to say since the last time this function was called this amount of time has elapsed so we're going to increment our time display just by however much time has elapsed so if we're getting i don't know 30 frames per second this value will be zero point zero three two three three three three if we're getting 60 frames per second it'll be zero point zero one six six six six six six six six seven right all we're doing is adding whatever the value of time display is plus this number which will be a very small number since we're going to update this value hopefully 60 times in a second maybe more that'll give us like a counting up effect like you see all the time but remember that we have this speed that i told you we were going to use to modify how quickly we would count up what we'll do then is do time display plus time.deltatime times speed that'll allow us to control from the time display perspective at least how fast we're going to count up if we set this to zero though remember it's not going to change at all if we set it to anything greater than zero we're going to take that really small number from time.deltatime and multiply it by this number so if we set it to be a number below one that's going to make it go really slowly but still counting up if we said to be like 100 then it's going to count up very very quickly because if we're getting 60 frames in a second it's going to go 100 times faster than that be like getting 600 frames a second c also respects your favorite acronym from i don't know fifth grade early math pemdas maybe you heard please excuse my dear aunt sally something like that that means that time dot delta time times speed will happen first because that's multiplication right parentheses exponent multiplication so multiplication happens and then we do the addition and that's exactly what we want we want the time dot delta time timespeed to happen and then add that into the time display we only need one more line of code to actually make this do what we want it to do so we've really only written one line of code and one if statement so far right everything else has been just variable definition what we're gonna do is actually display this time display now on the text mesh pro so we're gonna do text dot and let's talk about the dot before we go any further so on time dot delta time we did time which is the class name right like in our case would be count up dot that dot tells the computer i want to access a class member variable or a function on that class from the class time in this case delta time is a class member variable that is public on the time class that's all that the dot is doing it's saying computer for this class or for this variable whatever it is i would like to access some of the class member variables or a function on that class in this case we want to update the text of the text mesh pro so we're going to say text dot saying hey computer please tell me what can i do on the text mesh pro u gui component and it will tell us set text is something we can do that will change the text of this text mesh pro component since set text is a function we want to call a function that's what it's called when we're going to execute a function so update is called once per frame by unity we are now going to call that means execute the set text function on the text mesh pro u gui component however many frames per second we're getting so to do that we do these parentheses and inside of those parentheses we need to say what do we want the text to be because set text is asking for one variable to be passed in whenever passing something into a function we call this either an argument or a parameter i don't know why it's an argument to send something to a function but that's what it's sometimes called you'll also hear them called parameters so in this case it's taking one parameter or argument the problem though is time display is a float so if we just put time display it's going to complain at us you'll see this red underline and if we mouse over that it'll say cs1503 argument one cannot convert from float to string which is good because it's actually telling us what the problem is it's telling us that set text expects there to be a string but we're giving it a float so how do we fix that luckily for us c sharp provides on floats a way to convert from a float to a string because remember float's just the number it's not text it's a number text has to have quotes around it so what we're going to do is say time display dot because we want to access something that is on a float and you'll see that there's the ability here to do tostring that's exactly what we want what this does is converts whatever type we have to a string in this case a float to a string and then a pair of parentheses because this is a function we need to call it so that's doing is calling the tostring function on the time display float and that will then return a string to the set text function from the text mesh pro u gui component the problem with this code though is the text as output isn't very readable this is primarily because the text doesn't always have the same size let's say that it's 0.123 on the next frame maybe it's 0.135763 if that's the case then we're going to have some jitter as the number changes because we're showing the least number of significant digits in that float so what we need to do is actually format this string so we'll have a consistent number of decimal places if you think back to some of the early math classes that's something we did by it would either round or truncate off after a certain number of digits your math teacher maybe told you only give me four digits we want to do the exact same thing here with this string we want to tell the computer only display a certain number of digits after the decimal because after that we don't really care anymore to do that we're going to use a numeric format specifier on this to string what that means is the tostring function here accepts a string that will tell it how it should format the string i'm going to pull up the microsoft documentation on how this works if we pass to the tostring a string that says n and then the number of digits we want to display it will automatically format our float value to be something like from this documentation one two three four dot five six seven if we used n three in my case i'm going to choose n two because i think two is a good number of numbers after the decimal to show when we're talking about time since the two string function wants a string as well we need to pass a string value you define a string value with quotes we're telling it please use this exact text that's in between these quotes so in this case we're gonna use the capital n and 2 because that's what microsoft tells us we need to do to make this do what we want this is what i was talking about earlier that the documentation both microsoft and unity have are really essential resources when you're working through your programming journey and of course i have some links to everything that we've talked about in the description if we open up the unity editor and i select the text tmp game object that has my text mesh pro text on it i will click add component and we'll see that my new script count up is accessible if i start typing count up if i select that just like any other component it'll show up on my list of components on my game object we'll see that we don't have that text reference so i'll drag the text message pro to that text reference and i'll click play once it starts we'll see that the numbers immediately start counting up where we only have those two decimal places because of that n2 that we passed to the tostring and we can of course adjust the speed just like we would normally see in the inspector anytime that we have normal numbers we have this kind of number input field if we increase the speed it goes faster if we lower it it goes slower if we set to a negative number or zero it will stop updating with that we've made our very first script ever that will allow us to make some text count up over time and it shows a pretty cool animation where the numbers kind of flicker as it's counting up hopefully that was really clear each step of the way exactly why we were doing each thing that we were doing it's totally okay if you had to pause re-watch stuff re-read the documentation all that's totally normal as you're starting to learn how to write code even today with i i've been writing code for almost 20 years now and still i will review documentation i'll have to look up stuff you don't need to feel ashamed if you need to go to google and ask google how do i do some something i do that to this day and i don't lose anybody that just knows how to do every single thing that they want to do the most important thing that i hope you took away from this video is not how to write a class how to serialize private variables write an if statement or make text count up what i hope you got from this video was actually that there are resources available to you to help you do whatever it is you're trying to do especially at like the basic level whenever we're just getting started writing code most of the time unity and microsoft have documentation supporting you doing whatever it is that you want to do they might not have specifically here's how you make text count up but they will have something saying hey here's how you update the text of a text mesh pro text here's how you can format that number and you can put those two pieces of data together running in the update loop and that's how we have it count up so what i mean to say by that is reading documentation while maybe not like the sexy topic to do is very important and it's very important to be able to do that efficiently so you can get the outcome you're looking for when a programming language or a game engine has really good documentation that makes it significantly easier to achieve an outcome because then you can just understand what do they allow me to do what is the interfaces i have to work with that's like the text mesh pro has a set text function that's part of the text mesh pro interface what options do i have available what functions can i call and when you understand that you can put together your existing knowledge plus this new knowledge you got from the documentation to achieve some new result that you're trying to get there might not always be a tutorial about exactly what you want to do so there's a little bit of problem solving involved here to think about what is it you're trying to do take the knowledge you have take your documentation put those two things together to achieve that result if you can master that and it will take some time then you'll be a coding expert i almost forgot to assign you the homework assignment the first link in the description is going to be the homework link it's going to take you to a random documentation from unity i want you to make a new script using that to show me a random number every frame rounded to three decimal places you've learned everything you need so far to get that done you just need to read a little bit about the random documentation to see how to get a random number drop a comment down below with your completed assignment and a link to a video showing your code and the random number displaying on some text match pro text no cheating i know for sure there's a video about this out there do it on your own that's how you're going to learn if you have value out of this video please consider liking and subscribing to help the channel grow reach more people and add value to more people this new video is posted every tutorial tuesday and i'll see you next week
Info
Channel: LlamAcademy
Views: 18,593
Rating: undefined out of 5
Keywords: Unity, Tutorial, llamacademy, C#, Basic Coding, Introduction to coding, coding for beginners, csharp, c sharp, intro, getting, started, easy, beginner, game, development, gamedevelopment, learn, course, program, programming, coding, code, write code, write, absolute beginner, absolute, newbie, noob, newb, friendly, language, first, get, get started, software, games, unity coding for beginners
Id: SXaa61JWLDw
Channel Id: undefined
Length: 30min 19sec (1819 seconds)
Published: Tue Jan 25 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.