Search Unity

arrays and #pragma strict

Discussion in 'Scripting' started by Brian-Kehrer, Nov 30, 2007.

  1. Brian-Kehrer

    Brian-Kehrer

    Joined:
    Nov 7, 2006
    Posts:
    411
    Is there a way to describe the type of the objects contained within an array?

    I have an array of a class I call "Item", with itemType as a variable within the class

    Code (csharp):
    1.  
    2.  
    3. ItemArray[Item_1].itemType
    4.  

    This code produces this error

    Assets/menuSystem.js(891) error BCE0019: 'itemType' is not a member of 'Object'.

    Is this a totally trivial problem?
     
  2. forestjohnson

    forestjohnson

    Joined:
    Oct 1, 2005
    Posts:
    1,370
    Code (csharp):
    1.  
    2. var theItem : Item = ItemArray[Item_1];
    3. print(theItem.itemType);
    4.  
     
  3. Brian-Kehrer

    Brian-Kehrer

    Joined:
    Nov 7, 2006
    Posts:
    411
    Sorry, I wasn't clear...

    I'm using dynamic arrays. Do they only take type 'object'?

    If so, I find it odd that a dynamic array should cause pragma strict to fail if there is no way to declare type, short of using static arrays, of course.
     
  4. joe gamble

    joe gamble

    Joined:
    Jan 3, 2007
    Posts:
    85
    you should be able to do something like this:

    var theItemArray : Array = new Array();
    theItemArray.push(theItem);
    var theItem : Item = theItemArray[0];
    print(theItem.itemType);
     
  5. Brian-Kehrer

    Brian-Kehrer

    Joined:
    Nov 7, 2006
    Posts:
    411
    hmmm, if that's the case, I'm probably not gaining anything in terms of performance over leaving it as dynamic typed.
     
  6. freyr

    freyr

    Joined:
    Apr 7, 2005
    Posts:
    1,148
    Well yes you will gain some performance.
    Code (csharp):
    1.  
    2. // Dynamic typing
    3. some_array[2].DoSomething();
    4. // vs. static
    5. var item : TheType = some_array[2];
    6. item.DoSomething();
    7.  
    The benefit from static typing comes from that in the examples above, the DoSomething method has to be looked up by name at runtime in the dynamic case, but is already resolved at compile time in the static case.

    This has nothing to do with the values being temporarily cast to Object while inside the array. It's not until you try accessing member variables or calling methods on the objects the actual type information is needed.
     
  7. Brian-Kehrer

    Brian-Kehrer

    Joined:
    Nov 7, 2006
    Posts:
    411
    thanks for the clarification keli-- I'd recommend including that in the performance optimization section for dynamic vs static type--at the very least for programming n00bs like me.
    It's a huge help when you guys explain why these things are so (as you just did), particularly for people new to scripting--it makes everything feel less arbitrary.