Menu
CoddyTech

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 icon

Challenge

Easy

Make the plant keep growing.

  1. Cut the line int frames = 0; from inside Update().
  2. Paste it above void Update(), inside the class, so frames becomes 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

Practice on your own: Unity playground