Im wondering if someone could explain Transform.position.x to me. Why is it so inaccessible ?. For example why does this not work? Is there a way to make this work… Im new to Unity and C# so please talk to me like a child. I mainly use C++ and Py.
Position is of type Vector3, which is a value type, not a reference type.
Furthermore, position is a property of Transform (not a field). A property is a dual function with methods for both ‘set’ and ‘get’ of a field… designed to syntactically look like a field, but act like methods.
As a result, when you access ‘position’, you’re actually calling a function that returns the Vector3 for its position. This Vector3 is a COPY of the actual class level field that the position is stored as, rather than a direct reference to the class level field.
So when you set the x of the Vector3, you’re setting the x of a copy of the actual Vector3 that the position is stored as.
So what you need to do is ‘get’ the copy, modify it, and ‘set’ it back.
var v = this.transform.position;
v.x = Mathf.Lerp(v.x, positionAttractUp.transform.position.x, Time.deltaTime * 4f);
this.transform.position = v;
Technically C# has ways to pass references of structs, but it requires it to be a parameter of a method (ala the ‘ref’ and ‘out’ keywords), OR as a pointer using the ‘unsafe’ keyword, which if I recall correctly should be avoided for the most part in Unity… I think it doesn’t compile in AOT well or something. Not sure… haven’t really required it in unity ever.
Note in UnityScript, the compiler gets around this with syntax sugar. It compiles the simple one line of code into the correct opcodes to pull, modify, and set.
Transform.position is a Vector3 struct, and struct are value types not reference types. Internally, transform.position is a property as well. When you call transform.position, you’re actually returned a new copy of a Vector3 struct describing the position… so modifying that value directly won’t modify the actual transform’s position.
What you have to do is assign a new Vector3 struct.
transform.position = new Vector3(new x position you want, transform.position.y, transform.position.z);