Very basic question

Hi

I am new to unity and javascript and was confused after seeing the colon(:slight_smile: operator many times in a script. Can someone tell me what it does? for example in this line:
var otherScript: OtherScript = GetComponent(OtherScript);

What does the colon do here?

var otherScript : OtherScript = GetComponent(OtherScript);

“I would like a new var(iable) named ‘otherScript’. It should be of the class ‘OtherScript.’”

The equivalent in C syntax would be:

OtherScript otherScript = etc.;

It doesn’t actually “do” anything, it’s just part of the required syntax for declaring a new variable (like ‘var’ is).

(Okay technically it’s not required; if you just have ‘var otherScript’ then otherScript can have any class assigned to it, which decreases script execution speed and ease-of-debugging, so don’t do it unless you have to :p)

It signifies the end of a line and is thus a part of the syntax

That’s what the semicolon does.

The colon is used to declare the type for a variable.

var foo : float; // "foo" is a float

Note that explicitly declaring the type is optional if you supply a value, since type inference supplies the type for you:

var foo = 10.0; // "foo" is a float, again

Just to head off the inevitable: this is NOT dynamic typing. It’s a compile-time feature (also supported by C#), and has no performance drawbacks. However you should always explicitly supply the type if there’s any confusion as to what the type is, in order to make debugging easier.

This, on the other hand, is dynamic typing–since neither type nor value is supplied–and will either fail to work in some cases, or be quite slow in those cases where it’s allowed:

var foo; // "foo" is dynamically typed

So don’t do that.

–Eric