Modify the Y position of a GameObject on startup

I'm trying to modify the Y position of a GameObject on startup with the script below:

int y;

void Awake()
{
y = Random.Range (140, 155);

Vector3 temp1 = transform.position;

temp1.y = y;
}


This script does not modify the Y position of the GameObject on startup. What can I do to fix this?

In Unity, the Vector3 type is a structure, not a class. In C#, structures are value variables, not reference variables. That means the = operator creates a copy.

In the line Vector3 temp1 = transform.position; you are creating a copy of the position. Any changes at that copy are not reflected in the original position. When you want to modify the position, you need to copy it back:

    Vector3 temp1 = transform.position;
temp1.y = y;
transform.position = temp1;


Your code, as it is, isn't actually moving anything. You're assigning a Vector3 and modifying it's Y value, but you're not altering the Y value of the GameObject's transform. Having said that, you can't simply say:

transform.position.y = y;


Because Unity won't let you. Best way to do this for a beginner would be:

void Awake()
{
int y = Random.Range(140, 155);
transform.position = new Vector3(0, y, 0);
}


That code will move the object to which this script is attached to a random Y position between 140 and 155, with X and Z both at 0. If you want the object to stay where it is in the world, but only move on the Y-axis, use:

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


Instead. This will move the object to which this script is attached to a random Y value without altering it's X and Z values.

• For the last code snippet I would recommend to use transform.Translate instead. – Philipp Jun 17 '16 at 9:30
• Well, that depends on whether or not you want to set it to be that exact position, or if you want it to move that many units. If they want to move the object rather than set its global position, then yes, you're absolutely right. – DisturbedNeo Jun 17 '16 at 9:33