- Home /
transform.localScale.x - can't change it
Hello, I'm trying to change the direction of a character through this: transform.localScale.x *= -1; The error that I get is : "cannot modify the return value of transform.localScale because it's not a variable"
it works with this code: Vector3 myScale = transform.localScale; myScale.x *= -1; transform.localScale = myScale;
From my point of beginner's view, these 2 code sequences make the same thing. Please kindly tell me why I can't change the code, using the first version. Thank you !
Answer by HenryStrattonFW · Jun 03, 2017 at 06:12 PM
The reason you cannot do this is because transform.localScale is a property, not a direct link to the variable itself, so its sort of like the same thing as calling a function like "GetLocalScale()" where the return value is the localScale. Fortunately properties can have get and set parts to them, however when used with structs, you have to set the whole value, you cannot just set a part of it. So the simplest way I've found to do what you're trying here is just to use a temporary Vector3 like this:
Vector3 lTemp = transform.localScale;
lTemp.x *= -1;
transform.localScale = lTemp;
Hope this helps.
I prefer transform.localScale = new Vector3(-transform.localScale.x, transform.localScale.y, transform.localScale.z)
I think Henry's snippet is more readable. Such a long line and somewhere in that line is a tiny -
that can easily be overlooked.
A shorter one-liner would be:
transform.localScale = Vector3.Scale(transform.localScale, new Vector3(-1,1,1));
You're right, It's my bad habit to code the shortest than possible.
Although in your solution you are guessing that the transform.localScale.y and .z are 1
Your answer
Follow this Question
Related Questions
clamp limit variables trouble 1 Answer
Crouch Script/ Scaling transform from one side only 1 Answer
Prefab color is black 1 Answer
Can't get Object size to Reset to Original 1 Answer
How is localScale adjusted when re-parenting transforms? 2 Answers