- Home /
Convert localScale to float?
I would like to convert a transform.localScale value into a float. I'm very new to unity and JavaScript and these variable types are driving me insane. I'm use to GameMaker's simplicity because all the variables in that program are basically the same type so you don't have to worry about different types conflicting.
I've also been running into this kind of problem with all kinds of variables because I just don't know how you normally handle converting value types. So if there's a reference somewhere someone could show me that explains how to convert values between common variable types I would greatly appreciate it.
Thanks!
Answer by aldonaletto · Oct 01, 2011 at 10:04 PM
localScale is a Vector3 - it's composed by 3 floats, x, y and z. This type is used by Unit to hold points, vectors and other x y z things - like scale and rotation angles: you can scale in or rotate around x, y or z axes, so storing these values in Vector3 makes sense.
You could have a single float to represent the equivalent scale - but only if the scale was the same in all three axes (what is a very commom case). If you want to set the scale at once, you can use this:
transform.localScale = Vector3.one * scale;
This will multiply the vector 1,1,1 by your scale, so all three components will become equal to your scale value (if scale = 0.35, the result will be 0.35, 0.35, 0.35).
The other way around - converting localScale to a float - can be done assuming that the scale is uniform (all three values equal): just read one of them and assign to scale:
scale = transform.localScale.x;
Or, you can use transform.localScale.magnitude- but be aware that it will give you funny results if the scale is non-uniform.
Thanks for the detailed response aldonaletto! I'm still trying to get my $$anonymous$$d around all the different variable types and what data they hold.
I totally forgot about how you can access just part of a vector using .x/.y/.z That seems to have solved the problem because I just remembered that not all scale values are the same and that unity would always give me a "can't convert" error every time I tried getting the whole vector as a float, but only getting part of the vector works fine.