x


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.

more ▼

asked Jul 01 '11 at 02:30 AM

Irsan gravatar image

Irsan
65 39 42 50

Is your script derived from MonoBehaviour?

Jul 01 '11 at 02:37 AM Dreamblur

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.

Jul 01 '11 at 03:52 AM aldonaletto
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

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;
}
more ▼

answered Jul 01 '11 at 02:39 AM

Eric5h5 gravatar image

Eric5h5
80.3k 42 132 521

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

Jul 01 '11 at 03:38 AM aldonaletto
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x822
x302
x211
x30
x1

asked: Jul 01 '11 at 02:30 AM

Seen: 947 times

Last Updated: Jul 01 '11 at 03:52 AM