Unity4.6 how to fix ArrayList elememt return null ?

Can someone tell me why “linearray[1]” and “linearray [1] as Line” return null, but when I print out “linearray.Count” it say it has 4 elements inside why? and how can I fix it and get the 1 element without return null thanks.

public class publicCar : MonoBehaviour {
  private ArrayList linearray;

    // Use this for initialization
    void Start () {
 

        linearray = new ArrayList ();
        linearray.Add (new Line (new Vector3 (0, 0, 7.2f), new Vector3 (21 * 34, 0, 7.2f)));
        linearray.Add (new Line (new Vector3 (0, 0, 4.3f), new Vector3 (21 * 34, 0, 4.3f)));
        linearray.Add (new Line (new Vector3 (0, 0, -3.72f), new Vector3 (21 * 34, 0, -3.72f)));
        linearray.Add (new Line (new Vector3 (0, 0, -7.06f), new Vector3 (21 * 34, 0, -7.06f)));


        Debug.Log (linearray[1]);
        Debug.Log (linearray [1] as Line);
        Debug.Log (linearray.Count);
    }
}
public class Line : MonoBehaviour {
    public Vector3 StartPoint;
    public Vector3 EndPoint;



    public Line(Vector3 a_sp ,Vector3 a_ep)
    {
        StartPoint = a_sp;
        EndPoint = a_ep;
    }
    void Start()
    {


    }
    public Vector3 EndP
    {
        get {return EndPoint;}
    }

    public Vector3 StartP
    {
        get{return EndPoint;}

    }

}

any reason you’re using an untyped ArrayList and not a typed List?.. you appear to be adding the same types so the faster typed List would probably perform better.

1 Like

Well, you can’t create MonoBehaviour-derived classes with new keyword, may be that’s the problem

1 Like

also your script should be throwing the following errors:

I’ve bolded the bit you really need to read.

1 Like

thanks for the help. just posting the answer so every knows

public class Line [COLOR=#ff0000] [/COLOR]{
    public Vector3 StartPoint;
    public Vector3 EndPoint;
    public Line(Vector3 a_sp ,Vector3 a_ep)
    {
        StartPoint = a_sp;
        EndPoint = a_ep;
    }
    void Start()
    {
    }
    public Vector3 EndP
    {
        get {return EndPoint;}
    }
    public Vector3 StartP
    {
        get{return EndPoint;}
    }
}