- Home /
Add one on local z axis
I wan't to add one to my players local z axis... Like:
void Start(){
Vector3 updatedPos = transform.localPosition;
updatesPos.z += 1;
transform.position = updatedPos;
}
This adds one on the z axis for the whole world (Can't remember what its called... opposite of local)
This might work :
void Start() {
transform.localPosition.x = transform.localPosition.x + 1;
}
It says I can't change it, and I need to consider storing it in a variable.
Yep I was not sure, js would let you do this but I know C# is far more strict about how you have to do things, sorry for the bad info :(
Answer by Uldeim · Nov 19, 2014 at 10:28 PM
Vector3s are immutable; you can't actually change their values. This is due to how they're implemented (as structs; ie. Value Types).
Try the following:
//Shorten the name
var locPos = transform.localPosition;
Vector3 updatedPos = new Vector3(locPos.x, locPos.y, locPos.z + 1);
EDIT:
Oops, the question was actually how to move along the object's z-axis, not to move it in local space.
The solution was to use the transform.Translate() method.
Just so we're clear, your code currently looks like this?
void Start(){
var locPos = transform.localPosition;
Vector3 updatedPos = new Vector3(locPos.x, locPos.y, locPos.z + 1);
transform.localPosition = updatedPos;
}
As other people have mentioned, the last line definitely needs to be localPosition and not position.
Answer by Jeff-Kesselman · Nov 19, 2014 at 08:25 PM
What is the difference between this line...
Vector3 updatedPos = transform.localPosition;
and this line?
transform.position = updatedPos;
Answer that question and you will know what is wrong with your code.
If its:
Vector3 updatedPos = transform.localPosition; transform.localPosition = updatedPos;
I already tried that. And it doesn't work! :(
Your answer
Follow this Question
Related Questions
yield WaitForSeconds c# 4 Answers
Find closest object with tag 1 Answer
Bullet Effect (RaycastAll Question) 1 Answer
Find children of object and store in an array 3 Answers
unity3d invoke 0 Answers