Search Unity

javascript scoping question

Discussion in 'Scripting' started by jago3d, Aug 24, 2009.

  1. jago3d

    jago3d

    Joined:
    Jun 11, 2009
    Posts:
    27
    Hi,
    i try to integrate some javascript code into a unity-script and have a scoping problem:

    Code (csharp):
    1.  
    2. function Update () {
    3. }
    4. function month(numdays, abbr)
    5. {
    6.   this.numdays = numdays;
    7.   this.abbr = abbr;
    8. }
    9. var monthList = new Array();
    10. var i = 0;
    11. monthList[i++] = new month(31, "Jan");
    12.  
    The problem is that "this" refers to the script, iso the funtion object. I get the error "numdays is not a member of "TestScript". How should this be coded correctly?
     
  2. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    1. You must declare variables that are meant to be used all over the scripts, outside the functions.
    You can not just use them and then they are "magically there"

    2. Are you sure you are using valid .NET code on the month part?

    UnityScript (unity's JS) is not website JS and does not offer any of its functionality and libraries
     
  3. jago3d

    jago3d

    Joined:
    Jun 11, 2009
    Posts:
    27
    Ok, so i cannot use "ordinary" JavaScript.
    Does Unity JavaSript offer a way to define structures or objects? The part of the listed code tries to instantiate initialise a custom defined structure named "month", containing a string and an integer.
     
  4. Eric5h5

    Eric5h5

    Volunteer Moderator Moderator

    Joined:
    Jul 19, 2006
    Posts:
    32,401
    Use classes instead.

    Code (csharp):
    1. class Month {
    2.    var numdays : int;
    3.    var abbr : String;
    4.  
    5.    function Month (n : int, a : String) {
    6.       numdays = n;
    7.       abbr = a;
    8.    }
    9. }
    --Eric
     
  5. jago3d

    jago3d

    Joined:
    Jun 11, 2009
    Posts:
    27
    Thanks!
    with the Class definition, and changing the way the Array is used it now builds.
    Code (csharp):
    1. var monthList = new Array();   
    2. monthList.Add(new Month(31, "Jan"));