Search Unity

Add/Push a new item in a ArrayList from C# to javascript

Discussion in 'Scripting' started by twintower31, Apr 3, 2008.

  1. twintower31

    twintower31

    Joined:
    Oct 31, 2007
    Posts:
    89
    Hi,

    I have a ArrayList defined public in a javascript, attached to a GameObject.
    I'd like to Add a new item to this arraylist from a C# script.
    I tried in C#:
    Code (csharp):
    1.  
    2. myJavascript  myscript = goPlayer.GetComponent(typeof(myJavascript)) as myJavascript;
    3. if (myscript.myArrayList== null) ... //-> true, the array is null so myArrayList.Add("foo"); // -> error indexoutorange
    4. myscript.anothervar=2; // works well
    5.  
    after creating the array in javascript with
    Code (csharp):
    1.  
    2. myArrayList=new ArrayList();
    3. myArrayList.Add("foo0"); // works well
    4.  
    Thanks for your help,
     
  2. jeremyace

    jeremyace

    Joined:
    Oct 12, 2005
    Posts:
    1,661
    The ArrayList wont return null unless the object itself hasn't been initialized, so check the myArrayList.Count instead.

    Also, create an accessor method (public function that adds the element) on the JS file.

    You shouldn't really access the ArrayList like that. So with the accessor, you call myScript.AddElement(type element); And your AddElement(...) method takes the data sent and adds it to the ArrayList.

    If you still have issues you should try pasting the full code. Pseudocode and partial code doesn't actually help all that much for debugging ;-)

    -Jeremy
     
  3. twintower31

    twintower31

    Joined:
    Oct 31, 2007
    Posts:
    89
    Ok,
    thank you for the tips,
    it works well right now.

    And I also did a mistake, my Array was badly initialised.

    I initialised the ArrayList in another function, instead of the part of the script declaration.