- Home /
Storing transform information in a variable?
I have a cube in my scene, and I want to get the x-scale in the form of a global variable. I used this:
static var BrickScaleX = (transform.localScale.x);
However, it doesn't work. This is the error message it gives me:
"Assets/GetScale.js(1,27): BCE0020: An instance of type 'UnityEngine.Component' is required to access non static member 'transform'."
I want to be able to perform math functions on the x-scale of the cube, but I can't do it this way.
In Unity, each script instance is a fresh copy of the original, including its public variables, while static variables are unique, like any old and good global. If you will have only one cube in your game with this script, the variable may be declared static, and thus be accessed by any other script. But if you may have several cubes, each one with its own brickScaleX, DON'T declare it static, or all cubes will write their localScale.x values in the same variable - do it like in the @Eric5h5 answer.
Answer by Eric5h5 · Jul 01, 2011 at 02:39 AM
Only declare variables outside functions; all actual code should be inside functions. Static doesn't mean global; only add static if you actually want only one instance of it per class. If it's public (which it is by default in JS), then it's global. Also, it makes things easier to follow if you follow the convention of using lowercase for variable names, and uppercase for function and class names.
var brickScaleX : float;
function Start () {
brickScaleX = transform.localScale.x;
}
Static vars in unity are the equivalent of global variables in the old plain C (and other languages): Global variables have program scope, which means they can be accessed everywhere in the program, and they are only destroyed when the program ends
Your answer
![](https://koobas.hobune.stream/wayback/20220612130621im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Accessing a variable of a script from another scene. 7 Answers
How can I access a GameObjects components using an instantiation variable? 4 Answers
[CLOSED] An object reference is required to access non-static member 0 Answers
How to compare variable component types between GameObjects at run time? 1 Answer
Accessing components via script and assigning randomized values to their parameters? 1 Answer