Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Very basic question

Discussion in 'Scripting' started by charakalmast, Sep 14, 2012.

  1. charakalmast

    charakalmast

    Joined:
    Sep 14, 2012
    Posts:
    2
    Hi

    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);

    What does the colon do here?
     
  2. Loius

    Loius

    Joined:
    Aug 16, 2012
    Posts:
    546
    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)
     
  3. wolfstien786

    wolfstien786

    Joined:
    Apr 12, 2012
    Posts:
    185
    It signifies the end of a line and is thus a part of the syntax
     
  4. Beennn

    Beennn

    Joined:
    Sep 11, 2010
    Posts:
    373
    That's what the semicolon does.
     
  5. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    The colon is used to declare the type for a variable.

    Code (csharp):
    1. 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:

    Code (csharp):
    1. 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:

    Code (csharp):
    1. var foo; // "foo" is dynamically typed
    So don't do that.

    --Eric