Variables

Variables

Variables are used to store data.

We want to store data all the time when programming. In games, we often find ourselves storing a player’s score, a character’s name, an actor’s location, a game state, etc.

The thing about data is that it comes in many forms. Data can be numbers, words, vectors, and even references to other actors. In order to handle all these types of data, variables must have a specific type. The type of variable tells you what type of data it stores.

Types of Variables

  • Boolean variables are either True or False.
  • Integer variables hold Whole Number values.
  • Float variables hold Decimal Number values.
  • String variables hold Words and strings of text.
  • Vector variables hold Vectors which are a set of 3 Float values.
  • Object variables hold references to Actors and other types of objects.

These are the most commonly used types of variables in UE4. Depending on what data you are trying to store, you’ll want to choose the right type of variable.

The types of variables of the examples given above:

  • A Score should be stored in an Integer or a Float variables.
  • A Name should be stored in a String variable.
  • A Location should be stored in a Vector variable.
  • A simple State like On/Off should be stored in a Boolean variable, while a more complex one may require an Integer variable.

Creating a Variable

Variables are created inside of blueprints, and thus are associated with that blueprint. For example, a player’s Score would be stored in the player blueprint.

To create the Score variable:

  • Open the + Add New menu in the My Blueprint panel of your blueprint
  • Select Variable
  • Name the new variable
  • In the Details panel, change its type to Integer or Float using the Variable Type dropdown

Now we can use the new variable in our code!

Using a Variable

When dealing while data, we’re either trying to get the data, or set the data.

When Getting data, we want to use it for some reason. Let’s say we want to print our Score when the game starts.

We first have to set up the nodes:

  • BeginPlayPrint String

Then we have to Get the Score data.

  • Drag the variable from the sidebar into the event graph.
  • Select Get
  • Connect it to the Print String > In String

Now we know how to Get the variable’s data in order to use it. Let’s work through Setting the variable to update it’s data.

Let’s say we want to add 1 to our score every time the ActorBeginOverlap event fires.

In order to do this, we have to:

  • Get our Score
  • Add 1 to it using an Integer + Integer node
  • Set the Score with the new value

Conclusion

You now know:

  • What types of variables hold what kind of data
  • How to Get the value of a variable
  • How to Set the value of a variable

You will use Variables all the time when programming. The best way to get comfortable with them is to keep creating and using them when needed.