Scale
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 33 of 85.
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
MediumMelt the ice cube down to 0.4, keeping it on the ground.
- Add a field
float size = 1f;. InUpdate(), setsize = Mathf.Max(size - melt * Time.deltaTime, 0.4f);. - Set
transform.localScale = Vector3.one * size;. - Keep its bottom at y = 0: set the position's y to
size / 2, keeping x and z.
Press Play: the cube shrinks and stays on the ground. 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
}
}
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