Beginning C# with Unity (2023 Edition) - Operators
Summary
TLDRIn this educational video, Vegetarian Zombie guides viewers through the basics of C# operators in Unity, emphasizing the importance of celebrating small coding successes. The tutorial begins with an assignment operator, then explores incrementing and decrementing variables, and introduces equality checks. Sponsored by cadeco.com, the video also includes a practical demonstration of creating a button in Unity and responding to clicks using a script. The lesson covers arithmetic operations, the modulus operator, string concatenation, and the order of operations. It concludes with a challenge to create a tip calculator, encouraging viewers to apply their newfound knowledge.
Takeaways
- 🎓 The video is an educational tutorial aimed at beginners in C# and Unity, focusing on the use of operators.
- 👏 It encourages learners to celebrate small successes and be patient with themselves as they progress in coding.
- 🔢 The video introduces the assignment operator, explaining how to use it to increment variables like hit points and experience points in a game.
- 💻 Sponsored by cadeco.com, a platform for developers offering learning resources on various development topics, including game development in Unity and Unreal.
- 🛠️ The tutorial demonstrates adding interactivity to a Unity project by creating a button and a script to respond to button clicks.
- 📝 It discusses the importance of understanding operators for game development, such as increment, decrement, addition, subtraction, multiplication, division, and modulus.
- 🧠 The video presents a brain teaser to illustrate the difference between postfix and prefix increment operators, highlighting a common source of confusion for new programmers.
- 🔄 The concept of integer division is explained, showing how it truncates decimal values, and the modulus operator is introduced as a tool for remainder calculations.
- 📑 The tutorial covers string concatenation and the need for manual spacing when combining strings with the addition operator.
- 🧮 Emphasis is placed on the order of operations in arithmetic, advising viewers to write clear and simple code to avoid confusion.
- 🔄 The cast operator is introduced for type conversion, with a cautionary note about data loss when converting from a larger to a smaller data type.
- 💡 The video concludes with a challenge to create a tip calculator, providing a practical application of the concepts discussed.
Q & A
What is the main focus of the video?
-The main focus of the video is to introduce the viewer to the world of operators in C# programming within the context of Unity game development.
Why is it important to celebrate small successes in coding?
-Celebrating small successes in coding is important because coding is hard and it takes time to understand concepts. Recognizing and rewarding progress helps maintain motivation and patience.
What is the assignment operator in programming?
-The assignment operator in programming, denoted by the equal sign, is used to assign the value of one variable to another, rather than to check for equality as in mathematics.
What is the purpose of the 'my operators' script created in the video?
-The 'my operators' script is created to demonstrate how to respond to button presses in Unity and to show how to increment variables using different operators.
How does the video explain the difference between prefix and postfix operators?
-The video explains that the prefix operator increments the value before the operation, while the postfix operator increments the value after the operation. It also cautions that the postfix operator can be confusing and recommends using the 'plus equals' operator for clarity.
Why does the video recommend avoiding the use of postfix operators when starting out?
-The video recommends avoiding postfix operators for beginners because they can be easily misunderstood, leading to bugs and confusion, especially when the order of operations is not clear.
What is the modulus operator and how is it demonstrated in the video?
-The modulus operator returns the remainder of a division operation. In the video, it is demonstrated by dividing 5 by 2, which results in a remainder of 1.
How does the video handle the addition of strings in C#?
-The video shows that when adding strings in C#, it is necessary to manually add spaces between the strings to avoid them being concatenated without any separation.
What is the importance of the order of operations in coding as discussed in the video?
-The video emphasizes the importance of the order of operations to ensure that calculations are performed correctly. It reminds viewers to follow the standard order (parentheses, exponents, multiplication/division, addition/subtraction) to avoid errors.
What is the cast operator and how is it used in the video?
-The cast operator is used to convert a variable from one data type to another. In the video, it is used to convert an integer to a float and vice versa, demonstrating how data loss can occur when converting from a larger to a smaller data type.
What challenge is presented at the end of the video?
-The challenge presented at the end of the video is to create a tip calculator that calculates the total amount including a tip based on the bill total and a tip percentage.
Outlines
📚 Introduction to C# Operators
The video, sponsored by cadeco.com, begins with a recap of the viewer's journey in learning C# and Unity, highlighting their progress from scripting basics to handling variables and types. The host, Vegetarian Zombie, encourages celebrating small victories in coding and introduces the concept of operators. The video then delves into the assignment operator, explaining its role in incrementing variables. It also touches on equality checking, which will be covered in future episodes. The sponsor, cadeco.com, is introduced as a platform for developers to learn various programming topics, including game development in Unity and Unreal. The tutorial proceeds with a practical demonstration of adding interactivity through a button in Unity, guiding viewers to create and attach a script that responds to button clicks.
🔗 Unity UI Interaction and Operator Basics
In this segment, the focus shifts to Unity's user interface, where the host guides viewers through attaching a script to a text element and setting up a button's 'OnClick' event to call a method from the script. The script is updated to include a method that increments a variable and displays its value, introducing the concept of shorthand operators for arithmetic operations. The video explains the difference between postfix and prefix increment operators, noting the potential for confusion with postfix operators. It advises beginners to use the 'plus equals' operator for clarity. The segment concludes with a brain teaser to reinforce understanding of operator precedence.
🧠 Understanding Prefix and Postfix Operators
This part of the video script discusses the nuances of prefix and postfix operators, emphasizing the importance of understanding their order of operation. It provides an example to illustrate how the postfix operator can lead to unexpected results if not used carefully. The video also covers the modulus operator, demonstrating how it returns the remainder of a division. The discussion extends to string concatenation and the importance of manually adding spaces. The segment ends with a reminder about the order of operations, advocating for simplicity and clarity in coding to avoid confusion and bugs.
🔢 Exploring Order of Operations and Casting
The script delves into the importance of order of operations in coding, using a social media puzzle as an example to explain the correct approach. It advises using parentheses for clarity and breaking down complex expressions. The video introduces the cast operator, showing how it can convert data types and the potential data loss when converting from a larger to a smaller type. The segment concludes with a challenge for viewers to create a tip calculator, providing a brief overview of the steps involved in setting up the calculator and connecting it to UI elements in Unity.
💻 Building a Tip Calculator in Unity
The final part of the script guides viewers through creating a tip calculator in Unity. It outlines the process of setting up a new script, adding variables for the bill total and tip percentage, and calculating the total amount including the tip. The video demonstrates how to connect the script to a button and text element in Unity, ensuring that the total amount is displayed when the button is clicked. It concludes with an encouragement for viewers to experiment with different approaches and to celebrate their progress, reminding them of the importance of writing clear and understandable code.
Mindmap
Keywords
💡Operators
💡Assignment Operator
💡Arithmetic Operators
💡Increment Operator
💡Equality
💡Variables
💡Methods
💡Unity
💡Casting
💡Modulus Operator
💡Order of Operations
💡Codeco.com
Highlights
Introduction to operators in C# programming
Importance of celebrating small successes in learning to code
Explanation of the assignment operator for variables
Sponsorship message from cadeco.com for developer learning resources
Adding interactivity by creating a button in Unity
Creating a new script called 'my operators' in Unity
Responding to button presses with a method in C#
Updating the UI text in response to user interactions
Incrementing variables and shorthand operators in C#
Understanding the difference between postfix and prefix operators
Demonstration of integer division and the modulus operator
Concatenation of strings using the addition operator
Emphasizing the importance of order of operations in coding
Advice on writing clear and understandable code
Introduction to the cast operator for type conversion
Challenge: Creating a tip calculator program in Unity
Setting up a tip calculator with public fields for bill total and tip percentage
Calculating the total amount with tip and displaying it on the screen
Encouragement to celebrate completing the first program
Transcripts
this video is sponsored by cadeco.com
[Music]
hey what's up everyone vegetarian zombie
here from learn create play to walk you
through the world of operators
but before we talk code let's review
Where We Are
when you started this course you were
probably new to C sharp and possibly
unity in that time you created a small
script to print messages on the screen
you started getting comfortable with
your code editor and you learned about
variables and types that's a lot so give
yourself a pat on the back coding is
hard and it takes time this means you
should really celebrate the small
successes and be patient with yourself
when it takes you a while to understand
things
now as is you know how to create
variables you can create variables for
hit points and experience points yet
what happens when the player kills the
boss how do you increase the player's XP
or how do you increase their hip points
when they take damage
welcome to the world of operators
there's a whole bunch of them but I'll
just introduce you to some of the more
common operators to get started we will
start with the equal sign in math we use
the equal sign to denote equality in
programming it's known as the assignment
operator let's take the following
statement mathematically the statement
doesn't make much sense a variable can
never equal itself plus one
instead what is happening is that you
are incrementing X Plus 1 and then you
are assigning the result of that
increment back to X
there's a way to check for equality but
that will come in a later episode
for now let's play around with operators
but before I do here's a message from my
sponsor codeco.com kadeco is a site for
developers made by developers with
hundreds of instructors from around the
world you can learn about topics such as
native iOS development native Android
development and even multi-platform
development with flutter
kadeco also features hundreds of free
articles including topics on game
development covering both unity and
unreal as a pro subscriber you can
access a library of thousands of videos
on a range of development topics the
curated learning paths are designed to
teach the basics of development in a
friendly and supportive way Pro
subscribers also have complete access to
all the books at codeco such as the
unity Apprentice that aims to teach you
Unity by creating a series of different
games get started on your programming
Journey today by heading on over to
codeco.com
okay we are going to start this demo by
adding a little interactivity to do this
we're going to add a button to our
project let's get started by opening
your project in progress
select the canvas game object in the
hierarchy and click the plus sign select
UI and then button text mesh Pro
good work now arrange the button so that
it is on the bottom of the screen
we're going to create a new script Now
call it my operators if you've been
following this course you should already
be familiar with creating Scripts
open up the script and update it to the
following
you've seen this before it lets us write
on the screen now let's write a little
code to respond to button presses
this is called a method we'll be
covering methods in later episodes The
key thing to note is all our code goes
between the curly braces return back to
the unity editor first select the text
and remove our Mad Lib script from it
simply find it in the inspector click
the three dots and select the remove
component option
next drag our my operator script to it
excellent now for the button
select the button and scroll down in the
inspector until you see the button
component
my button is named button one so I'm
just going to rename it for now
now look at the inspector at the very
bottom is something marked on click
click the plus sign beneath it
this provides some options don't worry
about what they do simply drag the text
game object to the bottom option
you'll see the drop down next to it
brighten up click the drop down then
find my operators
from the fly out menu select the display
message method
we've just told the button to call that
method when the user clicks on it that's
all I'm going to say about this right
now you are getting used to working with
unity's user interface from a very high
level you'll have to trust me on this we
want to focus on c-sharp and not get
lost in unity but we're doing lots of
important practice think of Danielson
from Karate Kid I'm thinking of the 80s
version I never saw the Remake when he
did all these monotonous chores when in
fact he was actually building the muscle
memory for his karate that's what we're
doing here
okay now Run the game and I use the word
game in the loosest of terms
and click the button
great we got a message on the screen
okay let's go back to our code
in our new method add the following
we've just created a new variable we
don't need a public or private modifier
inside a method you'll learn why in a
later episode now let's increase it by
10.
update the text
and Run the game
we get one thousand we've incremented
our variable you're going to do this a
lot so there is shorthand code for it
back in the code add the following
this is the same as the previous
statement it's just condensed we can
also subtract
multiply
or divide
there's nothing magical about the code
it's just shorthand to save you time now
if you want to increment just by one you
can use the postfix and prefix operators
here we've incremented the strength stat
by one
and here we get our strength increment
that's the prefix the post-fix also
increments the value
here's a brain teaser what will be
printed on the screen take a moment to
think about it now let's run it
look at that it's still 18.
now let's print out the strength
it's 19 now
let's take a look at what's happening
here our strength variable is set to 18.
then the value is assigned to the stat
variable
after the assignment the value is
increased by one by way of the
post-fixed operator
thus the post-fixed operator occurs
after any operation
let's take a look at this statement here
if strength was 18 in this case the stat
variable would then be 36.
after that multiplication and assignment
the strength variable would be
incremented to 19.
if you are confused welcome to the club
while the prefix operator is pretty easy
to grasp the post-fix operator can be
easily misunderstood there have been so
many bugs from misunderstanding their
applications that they were removed
entirely from the Swift programming
language yet they are in wide use in C
sharp so you need to know about them my
recommendation is to just use the plus
equals operator until avoid these
operators when starting out personally I
avoid them entirely
now let's play around with division take
this code
okay guess the result and yes this is a
trick question
when we run the code we get 2 not 2.5
this is because integers do not contain
any decimal information it's just plain
old numbers baby
any floating Point information is
dropped
now we have the modulus operator let's
change the division sign into the
following
When We Run the game we get one can you
guess what this operator does
it Returns the remainder of a division
operation 2 goes into 5 twice and
afterwards one is left over and that's
the result that the modulus operator
returns
the modulus operator is commonly used to
determine whether a number is even or
odd if the result is zero you know you
are working with an even number
so we've played with addition with
numbers but how about addition with
strings let's try it out
okay so what's going to print out on the
screen I asked pretending this isn't a
trick question but it totally is a trick
question let's run it
we get the name printed out but there is
no space between it we need to manually
add it update your code to the following
now one important thing to keep in mind
when working with operators is the order
of operations chances are you haven't
thought about it since school but it's
critical to your success you'll often
see images on social media declaring
only Geniuses can solve this when in
truth it's just an order of operations
question take this one
if you completely forgot about the order
of operations you may start on the left
hand side and work right
so in this case you might answer two
three minus 3 equals zero times six is
zero then plus two but that's the wrong
answer order of operation States
parentheses exponent division
multiplication addition and subtraction
so in this case we start with six times
three now there's no other
multiplication in division since
addition and subtraction are on the same
priority level it doesn't matter which
comes first so we can start left and go
right three minus 18 equals negative
fifteen plus two equals negative
thirteen we can write the same thing in
code
now let's run the game
and here's our result okay technically
that works but people sometimes forget
the order of operations and also it's
confusing at a glance opt for Simplicity
over complexity
whenever you find yourself getting too
clever with code remember that people
don't play games for the code they play
games to have fun now I might write a
problem like this
parentheses always goes first so use
parentheses to your advantage also don't
be afraid to break up complicated math
into separate statements
it might not look too Cody or hacker
Elite but again we're opting for
Simplicity by emphasizing Clarity your
code is easier for other people to
understand but more importantly it's
easier for you to understand trust me
and this happens to me all the time
months later you'll be reviewing your
own code and be pulling a Gandalf
impression this is why it's important
for yourself and others to write clear
code
lastly we have the cast operator this
converts types say you want to convert a
float to an INT you simply provide the
type you want to use in parentheses this
converts the integer 100 into a floating
Point number now if you try to convert a
larger type into a smaller type you're
going to lose data since a smaller type
can't hold all the information of a
larger type
the cast basically tells the compiler
that you accept the data loss
in this case we've converted a 32-bit
number into an 8-bit number
needless to say a lot of data was lost
okay that concludes operators but the
fun is just beginning for your challenge
I want you to create a tip calculator
create a public field that is a bill
total create another field that is a tip
percentage when the user presses the
button the total amount should be
displayed on the screen if you want to
take this to the next level create a new
script called tip calculator and make
sure to attach it to the text and
connect the button
and now as a hint this task requires
some casting pause the video now and try
it out
God
[Music]
you can't put out this fight
okay we're back and ready to create a
tip calculator believe it or not this is
your first actual program granted it's a
tiny one but it's a good first step okay
first I get started by creating a script
called tip calculator
I open the script set it up and add a
new method
I add it to our text
first I remove the my operator script
then I select the button in the
inspector I add the text back to the on
click event
from the drop down I select my object
and choose the calculate tip method
then I switch back
next I create two variables
okay here's where the magic happens
first we calculate the tip amount
variable by multiplying the amount
variable times the percentage variable
since the percentage variable is a float
we need to convert the amount variable
to a float as well as we can't multiply
a float with an integer next we
calculate the total amount we do this by
converting our tip amount variable to an
integer and adding the amount variable
and that's it switch back to Unity in
the tip calculator set the amount to
100.
now we get 120 as a total amount nice
work if you did something different but
it works no worries at all there's lots
of ways to do the same thing just make
sure to Pat yourself on the back and say
good job
in any case I hope you enjoyed this
episode if you did make sure to click
that like button and also if you want to
be notified about more c-sharp videos
make sure to subscribe and enable your
notifications I'll see you in the next
one
Ver Más Videos Relacionados
5.0 / 5 (0 votes)