Last Updated on 2021-11-03 by Clay
If we want to change the scale of the game objects in Unity, in addition to manual editing, we can change the scale with program.
Obtain the scale of game object
transform.localScale
returns the scale of the game object that the script attached. It is a Vector3 data type data.
// Gets the local scale of a game object
vector3 objectScale = transform.localScale;
If you want to obtain the other game object scale, you can use the following code:
// Gets the local scale of a game object
vector3 objectScale = OTHER_GAMEOBJECT.gameObject.transform.localScale;
Change the scale of game object
Since transform.localScale
is not a read-only attribute, we can assign value to it. The following is a code that scales all the original size to twice. Of course you can customize the size you want.
// Gets the local scale of game object
vector3 objectScale = transform.localScale;
// Sets the local scale of game object
transform.localScale = new Vector3(objectScale.x*2, objectScale.y*2, objectScale.z*2);
References
- https://www.codegrepper.com/code-examples/csharp/unity+get+scale+of+object
- https://docs.unity3d.com/ScriptReference/Transform-localScale.html
2hwhafr
I didn’t understand… but thanks for leaving a message!
Very clear and concise, straight to the point and an example of how it can be used.
Going on the forums can be a pain at times, and the docs can be too simple or not enough of the how and why.
I prefer sites that show the how and the why and with different implementations on how to use the code for further design problems.
Nice site!