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
EasyMake the sled's script compile so it stays on the floor and between the walls.
- Replace the two lines that set
transform.position.yand.xwith a copy:Vector3 p = transform.position;. - Set
p.y = Mathf.Max(p.y, 0.5f);andp.x = Mathf.Clamp(p.x, -4f, 4f);, thentransform.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
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