Can't access GameObject or Transform from ArrayList

Hi All,

I’m new to Unity so still learning the ropes.

I have an ArrayList to store clones of a prefab when they are instantiated. I’m simply trying to delete the clones and remove them from the ArrayList, but having a bit of trouble. Here is the code I’ve been playing around with:

ArrayList cacti;

void Start () {
        elapsedTime = 0.0f;
        cacti = new ArrayList();
}

void Update () {
        elapsedTime += Time.deltaTime;
        if (elapsedTime > 3)
        {
            cacti.Add(Instantiate(cactus, new Vector3(260, 0, -120), Quaternion.identity));
            elapsedTime = 0;
        }

        for (int i = 0; i < cacti.Count; i++)
        {
            GameObject go = (GameObject)cacti[i];
            if (go.transform.position.x < -300)
            {
                Destroy(go, 2);
                cacti.RemoveAt(i);
                i--;
            }
        }
}

The cacti objects have their own script which moves them across the screen. When they go off the screen, I want to destroy them and remove them from the ArrayList. The problem is that when I add them to the cacti ArrayList when they’re instantiated, they are added as a generic ‘object’, which doesn’t have any of the properties of GameObject or Transform.

Therefore I cast it to GameObject inside my for loop. The way its casted above compiles fine in C#, but when I run it in Unity, I get an error on that line saying:

InvalidCastException: Cannot cast from source type to destination type.

Unity seems to think that cacti is already a GameObject (which is correct). But when I remove the (GameObject) cast on that line, C# will not compile, it gives the error:
Cannot implicitly convert type ‘object’ to ‘UnityEngine.GameObject’. An explicit conversion exists (are you missing a cast?)
So Unity thinks that cacti is a GameObject, and C# thinks its an object. How do I get around this? Or is there a better way of keeping references to clones that are dynamically instantiated and destroyed?

Also should have mentioned, the script that I posted is a main logic script which I attached to an empty game object.

Use a List (of GameObjects) instead of an ArrayList, then you don’t have to cast anything.

–Eric

Thanks for your reply. I managed to get it working by using a List<> like you said. However, I had to make it a List instead of List, because it couldn’t cast the return value of Instantiate to a GameObject, only Transform. I then destroyed the GameObject by using Destroy(cacti*.gameObject, 2);.*

I guess “cactus” must be a Transform instead of a GameObject. Which is fine; saves having to do a GetComponent call if you’re accessing the transform a lot.

–Eric