Menu
CoddyTech

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 icon

Challenge

Easy

The 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);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Scripting Basics