return instruction causing error?

Hi,

I’m currently wrestling with a strange problem. I have a bucket algorithm which goes through a multidimensional array looking for objects based on criteria. However, when I tried to return an array from the function, I got a nullreferenceexception.

I did all kinds of trouble shooting and came to the conclusion that no matter what I return, I get the same error. I’m at a loss. I use the return statement everywhere, and suddenly this pops up.

I have pinpointed the error, it is the return instruction itself, not any following instruction. The calling function never gets anything back, nor is it continuing to execute. Comment out the return statement and everything runs fine. It is very weird.

Help would be much appreciated. In case you can make sense of it, here’s the code:

function DistanceSearch(xcoord,ycoord, wradius : float) {
	var returnArr : Array;
	returnArr = new Array();	
	
	var centerBucket : BucketPos;
	var checkBuckets : Array;
	checkBuckets = new Array();
	
	var cnt;	
	var tbucket;
	
	centerBucket = WorldToBucket(xcoord,ycoord);
	checkBuckets.push(centerBucket);
	
	for (cnt=0; cnt<bucketSearch.length; cnt++) {
			tbucket = Vector2(centerBucket.x+bucketSearch[cnt].x,centerBucket.y+bucketSearch[cnt].y);
			if (tbucket.x>=0  tbucket.x<=bucketArSize  tbucket.y>=0  tbucket.y<=bucketArSize) {
				checkBuckets.push(tbucket);
			}
		
	}
	var bucketcnt;
	var curbucket;
	var buckX : int;
	var buckY : int;
	var testobj;
	var testcoord : Vector3;
	var checkcoord : Vector3;
	checkcoord = Vector3(xcoord,0,ycoord);
	
	for (cnt=0; cnt<checkBuckets.length; cnt++) {
		buckX = checkBuckets[cnt].x;
		buckY = checkBuckets[cnt].y;
		curbucket = buckets[buckX][buckY];
		for (bucketcnt=1; bucketcnt<curbucket.length; bucketcnt++) {
			print("length: "+curbucket.length);
			print(curbucket[bucketcnt]);
		
			if (curbucket[bucketcnt]!=-1){
			
				testobj =curbucket[bucketcnt];
				testcoord = testobj.transform.position;
				if (Vector3.Distance(checkcoord,testcoord)<=wradius) {
					returnArr.push(testobj);
					
				}
			}
			print("escaped!");
		}
	}
	print("exited loop");
	return(returnArr);
}

After some more testing it seems like the error is triggered if I try to return a string or an array. Returning an object reference, a number of some format, and so on works fine.

I have run into problems returning strings before, are arrays also known to be problematic?

Thanks in advance!

It seems I can get around the problem by encapsulating the array in a helper class, like this:

class ResultPack {
	var resArray : Array;
	var length : int;	
}

… and then accessing the encapsulated array instead.

Still seems very weird that Unity wouldn’t accept me trying to return arrays and strings. What could be causing the problem…?[/code]