Unity Community


Results 1 to 6 of 6

  1. Location
    Cambridge, UK
    Posts
    373

    Constants in Javascript?

    Code:  
    1. static var RESET_TIME   = 2.0;

    I am presently defining constants like this. They are in a script named Constant.js, and I call them from other scripts like this:

    Code:  
    1. if (timer >= Constant.RESET_TIME)

    However I'm aware this isn't the most efficient way to do it. Is there any way of making proper constants in Javascript that can't be adjusted at runtime?
    UA2008 'Best Game Design' winner: tumbledrop
    Homepage: starfruitgames.com


  2. Location
    The sunken city of R'lyeh
    Posts
    2,061
    There's nothing wrong with what you're doing. In fact that's a proper and functional use of the static keyword.

  3. Unity Developer

    Location
    Copenhagen, DK
    Posts
    340
    Like Quietus said, computational wise there's nothing inefficient about what you're doing there. Though I would make the Constants class a singleton and make all of the "constant" variables into members of that singleton so that you can edit the values of them in the inspector. (Wish static variables were exposed in the inspector :( )

    Code:  
    1. var RESET_TIME:float = 2.0;
    2. var SOME_OTHER_CONSTANT:float = 5.0;
    3.  
    4. private static var instance:Constants;
    5.  
    6. function Awake() {
    7.  // singleton logic
    8.  if(instance) {
    9.   Destroy(this);
    10.   return;
    11.  }
    12.  instance = this;
    13. }

    Then you can access the constants by with Constants.instance.RESET_TIME
    Shawn White
    Editor Developer - Unity Technologies
    CapnRat (Twitter) (Google+)


    ShawnWhite @ #unity3d IRC


  4. Posts
    94
    I am used to ActionScript, so maybe this doesn't apply to UnityScript, but is there a "const" keyword? In ActionScript, I would do it this way:

    Code:  
    1. static const RESET_TIME:Number = 2.0

    (Sorry if I've been useless or confusing in this discussion!)
    Jason


  5. Location
    Netherlands
    Posts
    381
    Other than inspector exposure, is there an obvious reason to prefer singletons over static vars?


  6. Posts
    2
    Hey dude, just jumping over from AS as well, turns out Unity JS doesn't recognise 'const'.
    G

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •