Vector3 Is a Struct
Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 22 of 67.
Vector3 is a struct, a kind of type the C# journey did not cover. A struct is a value, like an int: assigning it copies all of it. After Vector3 b = a; b.x = 9;, a.x is unchanged, because b is a separate copy. (A class works the other way: two variables can refer to one shared object.)
transform.position is a property, and reading it hands you a copy of the position. So transform.position.x = 0; would change a copy that is thrown away at once, and C# refuses to compile it: error CS1612: Cannot modify the return value of 'Transform.position' because it is not a variable. The fix is to copy the position, change the copy and assign it back. This runner returns to the middle lane when Space is pressed:
if (Input.GetKeyDown(KeyCode.Space))
{
Vector3 p = transform.position; // copy
p.x = 0; // change the copy
transform.position = p; // assign it back
}Leave out the last line and the code compiles, but nothing moves: only the copy changed. transform.localScale and the other Vector3 properties work the same way.
Challenge
EasyThe sled falls at fall units per second, and the arrows slide it along x. Two lines should keep it on the floor (y never below 0.5) and between the walls (x from -4 to 4), but the script does not compile.
Press Play to see the errors. Fix the two lines by working on a copy of the position, keeping what they do, then press Check.
Try it yourself
using UnityEngine;
public class Sled : MonoBehaviour
{
public float speed = 4f;
public float fall = 3f;
void Update()
{
float h = Input.GetAxisRaw("Horizontal");
transform.position += new Vector3(h * speed, -fall, 0) * Time.deltaTime;
// Keep the sled on the floor and between the walls.
transform.position.y = Mathf.Max(transform.position.y, 0.5f);
transform.position.x = Mathf.Clamp(transform.position.x, -4f, 4f);
}
}
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