Trouble with passing generic array to function

Hi folks,

Having done due diligence I’ve not yet found my answer.

Here’s the issue:

Passing a generic array to a function to have it “filled” and then access the items in the array later.

I tried what I believe to be the same functionality in-line and hard coded and I’m able to access the items, however after the function runs when I attempt to access the items i get an error.

Here is the code that doesn’t work:

The variable declaration (outside of any function):

var n0						: Transform[];

Calling the function:

	fill_number_array("num_0", n0);

The function:

function fill_number_array(numParentName:String, numAry:Transform[]){
    
    	var numParent 	: GameObject	= GameObject.Find(numParentName);
    	var trs 		: Transform[]	= numParent.GetComponentsInChildren.<Transform>();
    	
    	dl("trs[0].name = " + trs[0].name);
    	
    	numAry = new Transform[1];
    	numAry[0] = trs[0];
    	dl("numAry[0].name = " + numAry[0].name);
    }

Then I try to access the first item in the array just below calling the function:

	dl("n0[0].name = " + n0[0].name);

And here’s the error:

IndexOutOfRangeException: Array index is out of range.
NumberLauncher_TM.Start () (at Assets/NrG/Scripts/NumberLauncher_TM.js:202)

Here’s the code that does work (not calling a function this time):

	var numParent 	: GameObject	= GameObject.Find("num_0");
	var trs 		: Transform[]	= numParent.GetComponentsInChildren.<Transform>();
	
	dl("trs[0].name = " + trs[0].name);
	
	n0 = new Transform[1];
	n0[0] = trs[0];
	
	dl("n0[0].name = " + n0[0].name);

Appreciate the time you folks spend helping folks like me.

Thank you.

You’re correct in thinking that the array would be passed by a reference when passed as a parameter, and thus any change made to that array would be reflected in the original.

However, what you forgot is that the references are value types. This means that the passed reference is a COPY of the original reference, thus the change you make in the function if made to a COPY of the reference to n0. So what happens in your code is at the end of the function, n0 and numAry point to a different array.

How you can make this work, is you need to return the changed reference from the function and store it in the main loop. Something like:

n0 = fill_number_array("num_0", n0);

//at the end of fill_number_array
return numAry;