Javascript question.

Ok so I know this may seem like a novis question but I just can’t seem to grasp variables. I get functions and all that but just can’t get my mind around variables. I know it’s like an empty box ready to be filled with data for easy access, but isn’t that almost the same as a function? Does anyone have a good way to explain this to make it easier for me to understand or know of good script snippets showing what the clear purpous of a function is.

any help would be much appritiated. THANKS!

A function is not a way to store data, it stores a section of code so that it can be used again repeatedly with ease. For example if I have a gameObject that I want to move to a new location each time it is hit, then I would create some code that would do that, and place that code inside a function, for example, function ResetPosition(){…}. Then whenever I needed to reset the objects position, I could just write ResetPosition(), instead of writing the entire code segment again. Hope this helps. In short, variables are meant to store small data pieces, like a number or a word, while functions store and execute sections of code. Hope this helps.

A function does something, while a variable stores something (a function may also return a value, but that’s another story - don’t worry about this now). Variables usually have a type: int holds only integer values (1, 5, 432), float holds real values (1.0, 0.2, 3.14159), String holds characters and strings (“a”, “hello”, “Bye”), and the Unity types can hold references to Unity components or objects (like Transform, Rigidbody, Collider, Camera etc.)

There’s an example of a function and a variable:

var speed: float = 60.0;

function Update(){
    transform.Rotate(0, speed * Time.deltaTime, 0);
}

The variable speed declared at the top stores a float number - the rotation speed, in this case.

The function Update is called by Unity before drawing each frame. We usually place inside it code that updates the screen or that must execute frequently. In this case, I called the transform function Rotate, which rotates the object around the axes x, y and z by the corresponding values in degrees: x = 0, y = speed * Time.deltaTime, z = 0, in this case. Notice that the object should rotate around the Y axis, and at speed degrees per second. Since Update is executed before every frame, Unity supply a special variable to help us: Time.deltaTime is the time elapsed since the last frame was rendered, and works as a “correction factor”: when multiplied by speed it ensures the rotation will be constant and equal to speed rotations per second.