Ghoul Fool
Ghoul Fool

Reputation: 6949

Transform syntax usage

I'm modifying the transform of a simple cube.

float gravity = -0.25f;
myCube.transform.position.y -= gravity;

Doesn't work. error CS1612: Consider storing the value in a temporary variable.

float temp = myCube.transform.position.y;
temp -= gravity;
myCube.transform.position.y = temp;

Doesn't work. Same error CS1612: Consider storing the value in a temporary variable.

//Create temp gravity vector
Vector3 temp = new Vector3(0.0f, -0.25f, 0f);
myCube.transform.position += temp;

Which DOES work and so does this

private Vector3 cubePos;        
float gravity = -0.25f;
cubePos.Set(myCube.transform.position.x, (myCube.transform.position.y - gravity), myCube.transform.position.z);
myCube.transform.position = cubePos;

I understand how I can modify the transform with a vector (third example) or adjust the position with Set. But I still don't understand why the second example fails.

Can anyone kindly explain where I'm going wrong here?

Upvotes: 0

Views: 698

Answers (2)

David
David

Reputation: 16277

The easiest way to translate a game object is:

myCube.transform.Translate(0, -gravity, 0);

Or

myCube.localPosition = new Vector3(
       myCube.localPosition.x,
       myCube.localPosition.y - gravity,
       myCube.localPosition.z);

References:

Upvotes: 1

Hamdullah shah
Hamdullah shah

Reputation: 804

"transform.Position.y" is a read only property so you can just read. Store the position in a Vector3 the modify that vector and then set it back to position e.g

Vector3 temp = cubePos.transform.position;
temp.x -= gravity;
temp.y -= gravity;

cubePos.transform.position = temp;

Upvotes: 2

Related Questions