C# transform

Hello everyone,

I’m currently porting a script from Java to C# (I only want to use one script type throughout my game). The Java script contains a line like this:

transform.position.z = 0;

When porting this line to C# (which basically should be the same line) like this:

transform.position.z = 0.0f;

I get the error:

Cannot modify the return value of ‘UnityEngine.Transform.position’ because it is not a variable.

So, what would be the way to change the value of z in transform.position using C#?

Thanks,
Metron

You can’t change some attributes in C#. Same goes for Color.r/g/b etc.

Quick fix is this:

transform.position = new Vector3(transform.position.x, transform.position.y, 0.0f);

Thanks… but… gosh… at least one new Vector per FixedUpdate…

Thanks,
Metron

Try this

Vector3 vec = transform.position;
vec.z = 0;

The problem with transform.position is that the property is :

public Vector3 position { get { return _position; } set { _position = value } }

It expects a Vector3 as value, but if you get a reference to it, you can modify its coordinates without having to pass a new Vector as value.

It’s because it’s a struct (not object); it’s just how it is (and I imagine UnityScript was working around this through boxing or something, so you weren’t doing yourself any favours anyway there). When you “get” position, you’re really getting a copy of it (so the compiler warns you that you’re modifying a copy and it’d be thrown away… albeit with a somewhat cryptic message)

Honestly though, because the vectors are such light structs, I don’t think you need to worry about performance.

EDIT: I doubt dart’s method will work. As Vector3 is a struct, and passed back as a copy via a getter, you can’t get a direct reference to the underlying field.