Help conceptualizing built in arrays

Ok so I’ve been working with arrays for a couple months now, but I am pretty new to scripting in general, so I’m trying to figure out what exactly happens when arrays are built(or filled) – specifically built-in arrays vs. javascript arrays in unity.

Lets say I create a builtin array like this:

var colArray : Collider[] = new Collider[3];

So this built-in array has 3 slots now correct?

Okay, so now say I fill the slots with 2 colliders, doing something like this:

colArray = Physics.OverlapSphere(transform.position, 4, layer12);

And lets say it “hit” or picked up two colliders. What would be the length of my array now? Would it be 2 or 3? How would I determine (using code) how many objects are in my built-in array?

Now lets say we use the same example, but using a javascript array. If I have two colliders in my javascript array, what is the length of the array. Would it be 2? Or would it be 3?

Thanks for any help.

Correct.

Two. OverlapSphere returns a new array, so whatever you did with your colArray previously is wiped out, and replaced with the new array.

colArray.Length

Don’t use Javascript arrays, they are slow and obsolete. If you need an array which can be easily added to and removed from, use a generic List. Anyway, the same thing happens, except the Collider[ ] array returned by OverlapSphere is converted to a JS array.

–Eric

Thanks Eric. So one follow-up question, if OverlapSphere picks up 16 colliders, would the colArray be “re-built” to be 16 slots long, and have a “length” of 16, even if initially I declared it to have 3 slots at start?

Great information, thank you very much.

Yes. Technically, colArray is a pointer to the new array, and the old array is de-referenced (and will be cleaned up by the garbage collector eventually).

–Eric

Thanks Eric. That cleared some things up for me, I appreciate it.

I still have much to learn :slight_smile: