Menu
CoddyTech

Vector3 Is a Struct

Part of the Unity Scripting Basics section of Coddy's Unity journey. Lesson 29 of 85.

Vector3 is a struct, a kind of type you have not met yet. 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

Make the sled's script compile so it stays on the floor and between the walls.

  1. Replace the two lines that set transform.position.y and .x with a copy: Vector3 p = transform.position;.
  2. Set p.y = Mathf.Max(p.y, 0.5f); and p.x = Mathf.Clamp(p.x, -4f, 4f);, then transform.position = p;.

Press Play: the sled lands on the floor and the walls stop it. Then 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);
    }
}

All lessons in Unity Scripting Basics

Practice on your own: Unity playground