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