Well I have this line of code

            Vector3 pos = cell.CellPosition;
            float light1Height = 10f;
            pos.y = light1Height;

            lightGameObject.transform.position.y = light1Height;
            lightGameObject.transform.position.x = pos.x;
            lightGameObject.transform.position.z = pos.z;

The error states that

Cannot modify a value type return of 'UnityEngine.Transform.position". Consider storing the value in a temporary variable.

What should i do? Thanks!


Getting the property transform.position returns you a copy of the Vector3 position. Modifying the copy won't modify the original struct. You should therefore create a new Vector3 and replace the current position with it.

lightGameObject.transform.position = new Vector3(pos.x, light1Height, pos.z);

You can also store the value in a temporary variable.

Vector3 position = lightGameObject.transform.position;
position.y = light1Height;
position.x = pos.x;
position.z = pos.z;
lightGameObject.transform.position = position;

In C# when a struct is accessed via a getter (like transform.position), the compiler won't allow you to modify a member, because it has no sense to do that, because a getter of a struct return a brand new struct that you have to reference first. If you don't your brand new struct will stay inaccessible...


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.