Jump to content
  • Advertisement
  • 12/03/18 05:07 AM

    Unity Scripting: Working with Variables

    Engines and Middleware

    • Posted By Packt

    What is a variable? Technically, it's a tiny section of your computer's memory that will hold any information that you put there. While a game is running, it keeps track of where the information is stored, the value kept there, and the type of that value. However, for this chapter, all you need to know is how a variable works. It's very simple.

    This tutorial has been taken from Learning C# 7 By Developing Games with Unity 2017 - Third Edition and published by Packt.

    What's usually in a mailbox, besides air? Well usually there's nothing, but occasionally there is something in it. Sometimes, there are letters, bills, a spider, and so on. The point is that what is in a mailbox can vary. Therefore, let's call each mailbox a variable.

    In the game development world, some simple examples of variables might be:

    • playerName
    • playerScore
    • highestScore

    How to name a variable

    Using the example of the mailbox, if I asked you to see what is in the mailbox, the first thing you'd ask is, "Which one?" If I say in the Smith mailbox, the brown mailbox, or the round mailbox, you'll know exactly which mailbox to open to retrieve what is inside it. Similarly, in scripts you have to give your variables a unique name. Then I can ask you what's in the variable named myNumber, or whatever cool name you might use.

    Let's see how this is represented in our code. The first thing we need to do is create a new script in Unity, all the fun and magic starts here from these first steps:

    1. In the Unity project panel, under the Assets tab, we are going to right–click the empty space:


    1. Then we go to the Create menu and select the C# Script option

    2. A new file was created and it is ready to be renamed; this is very important and we need to always give a name to this file. For now, we can call it variableScript (the name we gave to this file doesn't interfere with the content on it, so we can we choose any name we want):





    1. Then we double-click the script file that we have just created.

    2. The MonoDevelop program will open with the script ready to edit:



    1. Make sure that the name that appears after public class is exactly the same name that you assigned inside Unity (in this example, we gave the name variableScript). In case we don't rename the script file right away when it gets created, Unity will automatically assign the NewBehaviourScript name:



    1. Now we are ready to create our first variable, we are going to name it myNumber. Make sure that your script looks identical to the following screenshot (for now, don't be concerned about the details of how to write this):



    1. Then save the file

    Note: When you name variables, try to come up with a name that most accurately describes what value your variable contains. Avoid generic names such as name, speed, and score. Instead, name them playerName, carSpeed, and opponentScore, respectively.

    A variable name is just a substitute for a value

    As you write a script and create a variable, you are simply creating a placeholder or a substitute for the actual information that you want to use. Look at the following simple math equation: 2 + 9 = 11.

    Simple enough! Now try the following equation: 11 + myNumber = ???. There is no answer to this. You can't add a number and a word. Going back to the mailbox analogy, write the number 9 on a piece of paper. Put it in the mailbox named myNumber. Now you can solve the equation. What's the value in myNumber? The value is 9. So now the equation looks normal: 11 + 9 = 20.

    The myNumber variable is nothing more than a named placeholder that can store some data (information). So, wherever you would like the number 9 to appear in your script, just write myNumber and the number 9 will be substituted.

    We can test this on the script that we had previously created, so let's do it:

    1. We start by selecting the script that we have created and then we double–click it to open inside MonoDevelop:



    1. Now we create a new variable called total and we don't need to assign any number to it because we want this variable to show us the result of our:


    1. After the void Start () function, we are going to write the math equation total = 2 + myNumber:



    1. Save the file, go back to the Unity program, and drag and drop the script file on top of the Main Cameraobject:


    1. Click Play and take a look at the Total variable:



    Although this example might seem silly at first, variables can store all kinds of data that is much more complex than a simple number. This is just a simple example that shows you how a variable works. We will definitely look at more complex variable types at later stages. Remember, slow, steady progress, baby steps!

    Creating a variable and seeing how it works

    Now using a different method, we are going to develop a script that shows us the result on the Unity console. Once again, don't be concerned about the details of how to write this; we are going to explain everything in more detail in future chapters. Just make sure that your script is the same as the script shown in the next screenshot:

    1. In the Unity Project panel, double-click variableScript. The MonoDevelop window should open automatically on variableScript.cs.

    2. In MonoDevelop, erase what we have done before and write the lines 7, 12, and 14, as shown in the following screenshot:



    1. Save the file.

    Note: The best way to save your script is by using a shortcut. If you are using a Mac, use command + S, and on Windows use Ctrl + S. We will be saving a new version of the script every time some changes are made to it, so it is a good idea to use a shortcut instead of saving through the Filemenu.

    We have added a few lines to our script. Before we check whether it works or what it actually does, let's go through line 7:

    public int myNumber = 9;

    In simple words, this line declares a new number type variable named myNumber and assigns a value of 9 to it. We don't want to worry about theory too much now and want to write more code, right? Agreed, but we do need to remember a few things first.


    To create a new variable, we first need to declare it by saying what type of variable it is, and as we explored before, a variable type represents the content. This means that the content for the myNumber variable is a number. The keyword for whole number variables in C# is int and for different types of content, we assign a different keyword. We also have to give our variable a name; myNumber is fine for now. You can use any name you want, as long as it does not contain spaces or special characters.


    We have created our variable, and now we are giving it a value. To assign a value, we use the equals sign followed by the value. In this case, it is 9. To close the line, use a semicolon; this is always necessary. The program reads our script one line of code at a time, and by using the semicolon we are telling the program that the line of code ends there.

    Click play!

    Quite an exciting moment! Go back from MonoDevelop to Unity and click the Play button. Unity should print out two lines on the Console tab, looking like this:


    Unity executed the code in the variableScript component on the GameObject just after you clicked Play. We can see two lines printed on the Console window. We wrote a piece of code asking Unity to print these two values the Console window. Let's look again at lines 11 and 13. Everything inside the brackets in the Debug.Log function will be printed to the Unity Console. It can be a number, text, or even an equation:


    So, line 11 is asking, "Hey Unity, print the result of 2 + 9 on the console!" Line 14 is using the myNumber variable's value directly and adding it to the number 11.

    Thus, the point of this exercise is to demonstrate that you can store and use whatever values you want using variables, and use their names directly to perform operations.

    How to change variables

    Since myNumber is a variable, the value that it stores can vary. If we change what is stored in it, the answer to the equation will also change. Follow these steps:

    1. Stop Unity by pressing the Stop button and change 9 to 19 in the Unity Inspector tab

    2. Notice that when you restart the game, the answer will be 30

    I bet you have noticed the public keyword at the very beginning of the line that declares the myNumber variable. Let me explain what it means. It's called an access modifier. We use these to specify the accessibility of a variable. The public keyword means that the variable can be seen by code outside our script. Look again at the Unity Inspector tab. You can see the value of myNumber there because it is public. The private keyword, however, means that the variable can be accessed only by code in the same class.

    Note: Private variables are not visible in the Unity Inspector tab. If you wish to control or view them, make them public.

    Watch for a possible gotcha when using public variables

    Unity gives us great flexibility with editing or reading public variables in the Inspector tab. You will be using public variables most of the time. Now, I want to make you aware of something that might give you a headache sometimes.

    Note: All public variable values are overridden by the Unity Inspector tab.

    Let's look back at line 6; we had assigned our variable a value of 9. This value will be copied to the Unity Inspector. From now on, the value from Inspector is taken into account and not the value in the script, even if you change it. Therefore, be careful as this is very easy to forget.

    In the Inspector panel, try changing the value of myNumber to some other value, even a negative value. Notice the change in the answer in the Console tab.


    This tutorial is an excerpt from "Learning C# 7 By Developing Games with Unity 2017 - Third Edition" by Micael DaGraca, Greg Lukosek and published by Packt.

    Get the complete eBook for just $10 (limited period offer).

    Thanks for reading! Learn more on the Packt Hub: Creating interactive Unity character animations and avatars [Tutorial]

      Report Article

    User Feedback

    There are no comments to display.

    Create an account or sign in to comment

    You need to be a member in order to leave a comment

    Create an account

    Sign up for a new account in our community. It's easy!

    Register a new account

    Sign in

    Already have an account? Sign in here.

    Sign In Now

  • Advertisement
  • Advertisement
  • intellogo.png

    Are you ready to promote your game?

    Submit your game for Intel® certification by December 21, 2018 and you could win big! 

    Click here to learn more.

  • Latest Featured Articles

  • Featured Blogs

  • Advertisement
  • Popular Now

  • Similar Content

    • By tspartant
      Hey everyone! My name is Ryan. 
      Visualistic Studios is looking for experienced developers of all talents to join a game development team focused on completing contract work for compensation. 
      Work Description
      Typically you will either be assisting the team or working on your own contract.
      We usually bid $16-$25/h, however contracts can go above and below that so all pay grades are welcome, just be realistic. 
      Short Term Contracts
      Long Term Contracts
      We have the highest priority for these skills right now
      Programming - Unity, Unreal Blueprints
      Environment Artist
      Character Artist
      Character Animation
      UI Artist
      3D Asset Optimization
      VR/Mobile experience is a plus. 
      The Process 
      All communication is done through discord. All tasks and design documents will be laid out in "HackNPlan" for organization. 
      Initially, you'll get in contact with me and answer a few questions so I can get a scope of your experience. Afterwards, our outreach team will start looking for jobs that fit your description. Nothing is guaranteed, but if we know you're interested we can start looking 
      Our Experience
      For the past 3 years I've been working in game development contracting, and the past year I've been working full time from home. Since then, I've received more and more contracts and I'm now at the point that I have too many for myself to handle. This sparked the idea of creating a game development team for contract work! I've also been running my own hobby company for 5 years, and have a lot of experience in team management. 
      Get in contact!
      Please fill out this form so we can get all of the information out of the way, then we'll get in contact with you!
      Thank you everyone for reading, hope to hear from you soon!
    • By addictCoderCS
      Hi there,
      I'm working on an web RPG. This is not and action RPG. 
      The problem is I work full-time as a software developer and while I may get some code for the game done at work, I'm still a little short on time. So I'm looking for a second programmer to help me out. Please no beginners. I prefer working with someone who has built a full game (client, game server, web services, db)
      Proficient in C# Proficient in .Net Core 2.X Experience with ASP.Net Core MVC Experience with ASP.Net Core Web API Experience with Unity 2018 Proficient in SQL and SQLite Proficient in EntityFramework Experience in AWS (RDS and EC2) Experience with IIS I'll handle the cost of any third-party services, domain names, etc. I'm just looking for a little help to get this game built in a reasonable amount of time. It will also be nice to bounce some ideas off each other.
      If you are interested, please send me an email: addictcodercs@gmail.com
    • By GameDev.net
      GameDaily.Biz spoke to Improbable about its new shortcuts to multiplayer game development for Unity and Unreal. 

      Improbable helps game developers build believable online worlds with its bespoke technology, SpatialOS. Now, that task is much easier and accessible for those building games on the technology with the recent release of the SpatialOS Game Development Kit (GDK) for Unity. With these kits, Improbable hopes that developers find it easier to create vast, dynamic and unique worlds.
      This GDK for Unity includes a 200-gamer, first-person project that allows developers to experiment and tinker with their ideas for what their vision of a multiplayer game will look like.
      GameDaily.Biz met with Improbable’s Head of Product Marketing, Paul Thomas, and Head of Comms, Daniel Nye Griffiths, to speak about the SpatialOS GDK for Unity, as well as the upcoming launch of the SpatialOS GDK for Unreal Engine.
      In its first week, the SpatialOS GDK for Unity achieved over 2,000 developer sign ups to use it. “What we're trying to do is basically make it really fast for people to build multiplayer games,” said Thomas. “It comes with all the multiplayer networking so that developers don’t have to do any multiplayer networking. It comes with feature modules to allow [easy] solutions to common multiplayer problems, like player movement and shooting. And it comes with a cool starter project where you have 200 players in a free-for-all scenario. You can obviously use the power of SpatialOS to scale that project up to more players, with NPCs, and things like that. It gives people a really good base to start building multiplayer games.”
      There are several games currently in development or early access that utilize SpatialOS. The first into Early Access was Spilt Milk Studios’ Lazarus, a space MMO where the player becomes a pilot in a universe that ends every week, complete with a map that’s twice the size of Austria. Additionally, Bossa Studios released its survival exploration game Worlds Adrift into Steam Early Access earlier this year.
      Also using SpatialOS is Scavengers from Midwinter Entertainment, a studio founded by former 343 Industries studio head and Halo 4 Creative Director, Josh Holmes; the game is heavily inspired by his Halo 5: Guardians’ multiplayer mode, Warzone. Right alongside that company, Berlin-based Klang Studios is working on Seed, a simulation MMO that, according to its developers, lets players “interact and collaborate to create a world driven by real emotion and aspiration.”
      According to Thomas, for those looking to use the SpatialOS GDK for Unity, there is no limit to  what their games can do with Improbable’s tech.
      “What we're doing is expanding the possible gameplay you can do. Traditionally, when you make a multiplayer game, you're constrained by one single server. So you can say you have a 64-player game with a handful of NPCs or you could have a world that's 3km by 3km. With Spatial, you can go beyond that, test a much broader canvas to start thinking about different gameplay.”
      “You can go for a massive online persistent MMO with 10,000 players and hundreds of thousands of NPCs, something very, very vast and big like that. But you can also have smaller experiences. For example, there's a lot of interesting space in just extending what you see in the Battle Royale genre and session-based gameplay.”
      Thomas continued: “Our partners at Automaton have a game in development called Mavericks. The interesting thing there is they have a Battle Royale with 1,000 people, but what I really find interesting is the gameplay mechanics they've put in, like footprints so you can track people. They've added a cool fire propagation mechanic so you can start a fire that  spreads across the map and changes the world. Or you can add destructible buildings and things like that.”
      “So I think even looking at smaller scale games, we add a lot of value in terms of the new gameplay you can start adding. I'm just interested to see what people do with this extra power - what they can come up with.”
      While Battle Royale games and MMOs are obvious standouts for genres that best fit with SpatialOS, Thomas introduced some other ideas of genres that could benefit from the technology.
      “I also think there's a space for very interesting MMORTSs as well,” he said. “An RTS where you have persistent systems, like telling AIs to do things and then coming back to them a week later and seeing what's happened is an interesting space.”
      “I also see interesting mobile experiences that could come up. Having these worlds where you lay down some interesting things and then come back a few weeks later to see how they've evolved and changed, and the massive player interaction. Say for example with Pokemon Go, we can actually roam around the world and battle on the streets. I can see something like that working very well. Again, these are just ideas we've had and talked to people about. It's about giving people that flexibility and the ability to explore these ideas.”
      Klang’s Seed
      Griffiths added the possibility of events in a game that will have a massive, rippling, and lasting impact on its world as something that has people excited. One example he gives is how someone on one side of the map can do something that’ll have a knock-on effect for the rest of the world in real time.
      “There's a whole bunch of different angles you can take, some of which are about much larger player numbers or a much larger map, but there are other things you can do which are taking a relatively constrained game experience, a smaller map, a smaller number of players and adding richness to the game as well.”
      In fact, this is something that Thomas refers to as a “persistent in memory database,” meaning that for every object in the game world, there’s a history. Two examples cited by Thomas: “...a player could chop down a tree and that tree stays disappeared forever. Or a player can kill a big monster that was raiding a town and that town no longer gets raided by that monster, and this changes the dynamics of the world. Worlds can have a history. That means players can have a lot more meaning in these MMO worlds.”
      “Normally in MMOs, they're kinda like roller coaster rides: you go into a dungeon, you kill the boss and that guy respawns. It all resets,” Thomas continues. “But in Spatial MMOs, you could have these persistent effects that should change the gameplay meaningfully for all the rest of the player base.”
      “The other one I think that is interesting is the level of dynamism that you could have. So because you can have so much more server-side compute, you could potentially have NPCs roaming around the world changing their mind and deciding all of a sudden, 'oh, we're going to attack this player's base' or 'we're gonna go attack this town' and they have a lot more range and emotion and intelligence to them that you'd not see in other MMOs.
      “Normally in MMOs, NPCs sit there tethered. You go near them and they come and attack you, you run away, and they go back to where they were. In a Spatial MMO, that NPC can trace you across the whole map or a group of them can decide to get together and attack someone..”

      Bossa Studios' Worlds Adrift

      Next week, Improbable plans to launch its SpatialOS GDK for Unreal Engine, which will have a big focus on ease of use for access to Unreal, as well as a big emphasis on porting your projects to SpatialOS.
      “One of the things we'll be trying to push is a porting guide so you'll be able to take your existing Unreal game, move it onto SpatialOS and then you can grow to expand it with new and extra gameplay,” says Thomas. “ You can bring across your existing Unreal game and it feels very, very native and similar to Unreal if you're familiar with Unreal.”
      Griffiths continued, explaining how testing these experiences includes free cloud deployments, to a certain point. “If you're developing in SpatialOS in other ways, we provide a sandbox environment so you can get your game running. When you’re happy, you can port it over and sort of experiment with it in a free sandbox environment with a small number of cores to get started.”
      Based on what we learned, Improbable’s SpatialOS GDK for Unity will give developers enhanced flexibility to produce more in depth and engaging videos games. That said, we look forward to catching up with the company in the near future to see how this exciting technology is being used in the different games that we play.
    • By Tedson Santos
      Hey Folks!!!

      We have a great news for you, we just released a Demo that is our last version of the game before the Early Access on Steam! This is Version 0.9d. The game had several modifications, We hope you like it!
      Download Link:


Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!