How does this Time.deltaTime dependent transform.scale script work?

495 Views Asked by At

I am studying Unity3D and C# and I'm trying to understand the inner working of this code. Can someone explain it to me?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// This script will shrink and grow the game object over time.
/// </summary>
public class Resizer : MonoBehaviour
{
    // fields for timer support
    const float TotalResizeSeconds = 1;
    float elapsedResizeSeconds = 0;

    // fields for resizing control
    const float ScaleFactorPerSecond = 1;
    int scaleFactorSignMultiplier = 1;

    void Update()
    {
        // resize the game object
        Vector3 newScale = transform.localScale;

        newScale.x += scaleFactorSignMultiplier * ScaleFactorPerSecond * Time.deltaTime;
        newScale.y += scaleFactorSignMultiplier * ScaleFactorPerSecond * Time.deltaTime;
        transform.localScale = newScale;

        print(Time.deltaTime);

        // update timer and check if it's done
        elapsedResizeSeconds += Time.deltaTime;
        if (elapsedResizeSeconds >= TotalResizeSeconds)
        {

            // reset timer and start resizing the game object
            // in the opposite direction
            elapsedResizeSeconds = 0;
            scaleFactorSignMultiplier *= -1;
        }
    }
}

Specifically, I'm trying to understand this part:

        newScale.x += scaleFactorSignMultiplier * ScaleFactorPerSecond * Time.deltaTime;

Thanks in advance for your help!

1

There are 1 best solutions below

0
On BEST ANSWER

scaleFactorSignMultiplier will alternate between 1 and -1 every time the "timer" is reached. When the accumulated time reaches above TotalResizeSeconds, the sign of scaleFactorSignMultiplier will change by multiplying it by -1 and this will control the scale direction between growing and shrinking.

ScaleFactorPerSecond is a constant which describes how fast the object will grow and shrink. Every second, this value will be added/removed from the object's scale.

Time.Delta is a system variable which tells the function how much time has passed since the previous frame was evaluated. This is required for determining how much scale to apply in this particular frame.