Scale
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 25 of 67.
transform.localScale multiplies an object's size along each of its axes. A default cube is 1 unit on every side, so a cube with localScale (4, 1, 0.5) is 4 units wide, 1 tall and half a unit deep. For an even size, multiply Vector3.one, which is (1, 1, 1). This soap bubble grows by 0.3 per second until it is 3 units across:
public float size = 1f;
void Update()
{
size = Mathf.Min(size + 0.3f * Time.deltaTime, 3f);
transform.localScale = Vector3.one * size;
}Mathf.Min(a, b) returns the smaller of its two numbers, so size grows until it reaches 3 and then stays at 3.
Scale works around the object's pivot, which for Unity's built-in shapes is the center. A 1 unit cube resting on the ground has its center at y = 0.5. Scale it to 3 units tall and it reaches 1.5 up and 1.5 down from there, so half of it sinks into the ground. To stand on the ground, its center must be at half its height: y = 1.5.
A child's size is multiplied by its parent's: a child with localScale (1, 1, 1) under a parent scaled by 2 is drawn twice as big. transform.lossyScale reads that final size in the world, and it is read-only; localScale is the one you set.
Challenge
MediumThe ice cube is melting. From the start of the game it shrinks on every axis by melt (0.2) per second, from its size of 1 down to 0.4, and then stays that size.
Shrinking around its center would leave it floating, so keep its bottom on the ground (at y = 0) the whole time. Its x and z do not change.
Press Play to watch it melt, then Check.
Try it yourself
using UnityEngine;
public class Melt : MonoBehaviour
{
public float melt = 0.2f;
void Update()
{
// Shrink by melt per second, down to 0.4, with the bottom on the ground
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Unity Scripting Basics
1Your First Script
Hello, UnityPlace the CubeMove Every FrameTurn Every SecondSteer with the KeysRecap: Drive the Cube4Vectors
Adding VectorsDirectionsLocal and World SpaceDiagonal SpeedDistance Between ThingsVector3 Is a StructRecap: Drone Pilot7Project: Catch the Star
The CatcherA Falling Star5Transforms and Hierarchy
Parents and ChildrenScaleLook At ThingsMove Toward a PointRecap: Orbiting Moon