Menu
CoddyTech

Variables

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 2 of 85.

A variable is a named box that holds a value: your lives, your speed, the height of a tower. You make one with a type, a name and a first value:

int lives = 3;

int is the type for whole numbers (3, 0, -12). lives is the name, = puts 3 in it, and ; ends the line, the way a period ends a sentence.

After that, the name stands for the value, as many times as you use it:

int height = 3;
int length = 6;
transform.localScale = new Vector3(length, height, length);

transform.localScale is the object's size: width (x), height (y) and depth (z). This block is 3 tall, 6 wide and 6 deep. Change length to 4 and it gets smaller in both directions at once, because both places read the same box.

Your code goes between the { and } of Start(). Lines that start with // are comments, notes that C# skips.

challenge icon

Challenge

Easy

Make the tower 5 floors tall and 2 wide.

  1. In int floors = 2;, change 2 to 5.
  2. In int width = 1;, change 1 to 2. Change only the numbers: a second int floors line is an error.

Press Play: the tower grows taller and wider. Then Check.

Try it yourself

using UnityEngine;

public class Tower : MonoBehaviour
{
    void Start()
    {
        int floors = 2;
        int width = 1;

        transform.localScale = new Vector3(width, floors, width);
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground