Search code examples
unity-game-engineunityscript

Can't access class variables through array of objects (unityscript/Unity)


Here is my class

public class ItemClass extends System.ValueType
{
    public var itemTexture : Texture2D;
    public var descriptionTexture : Texture2D;

    public function ItemClass (item:Texture2D, desc:Texture2D)
    {
        itemTexture = item;
        descriptionTexture = desc;
        //GUI.DrawTexture(Rect(179, 140, 200, 202), attHighlight4);
    }
}

Here is my array

var Test = new ItemClass(Axe, AxeDescription);
public var itemArray = new ArrayList();
itemArray.Add(Test);

If I try to access itemArray[0].itemTexture Unity tells me that itemTexture is not a member of 'Object'.

Looking for the syntax to access itemTexture.


Solution

  • You may find this wiki page helpful: Which Kind Of Array Or Collection Should I Use?

    ArrayLists contain 'objects'. When you retrieve your item back out of an ArrayList, it's unclear to the runtime or compiler what type that item was originally. You need to provide a more explicit type hint about the item, such as below:

    var myItem : ItemClass  = itemArray[0]
    var myTexture           = myItem.ItemTexture
    

    You might consider using List<> instead, for the reasons covered in the wiki page.