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
EasyMake the tower 5 floors tall and 2 wide.
- In
int floors = 2;, change 2 to5. - In
int width = 1;, change 1 to2. Change only the numbers: a secondint floorsline 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
1C# Basics in Unity
Hello, UnityVariablesDecimals Need an fText in the ConsoleVariables That RememberIf and ElseCompare NumbersRecap: Coin Collector2Make It Move
Place the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube5Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot8GameObjects and Components
References in the InspectorGet a ComponentMissing ComponentsAdd a ComponentRequireComponentShow and HideRecap: Light Switch6Transforms and Hierarchy
Parents and ChildrenHoist the FlagScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon9Project: Catch the Star
The CatcherA Falling StarPractice on your own: Unity playground