Variables That Remember
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 5 of 85.
Unity calls Update() every frame, and every call starts fresh: a variable made inside a method is thrown away when the method ends. So this counter never gets past 1:
void Update()
{
int frames = 0;
frames++;
}frames++ adds 1, the short way to write frames += 1. But the next frame runs int frames = 0; again and starts over.
To remember a value from one frame to the next, make the variable inside the class but outside every method. A variable there is a field: it lives as long as the object does, and every method of the class can use it.
int frames = 0;
void Update()
{
frames++;
}Now frames keeps counting: 1, 2, 3 and on, one more every frame.
Challenge
EasyMake the plant keep growing.
- Cut the line
int frames = 0;from insideUpdate(). - Paste it above
void Update(), inside the class, soframesbecomes a field that remembers its count.
Press Play: the plant grows a little taller on every frame. Then Check.
Try it yourself
using UnityEngine;
public class Grower : MonoBehaviour
{
void Update()
{
int frames = 0;
frames++;
transform.localScale = new Vector3(1, 1 + frames * 0.01f, 1);
}
}
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