Why my logic make unity3d death?

:shock:
hello, I make a logic to calculate the array. but I don’t know why it will make unity3d death when index= arr.length-1 ?

the code below:

var OrigiArr: int[];
private var UsefulArr = new Array();

function Start() {
	for(var a: int in OrigiArr) {
		UsefulArr.Push(-1);
	}
}

function Update () {
	if(Input.GetButton("Fire1")) {
		GetRandomCannonNo();
		DoFire();
	}
}

function DoFire() {
}

//for random cannon fire
function GetRandomCannonNo() {
	if(OrigiArr.length==0) {
		return;
	}
	makeUsefulCannonNo(0);
}

//callself
function makeUsefulCannonNo(UsefulIndex: int) {
	var tmpNo: int;

	if(UsefulIndex == 0) {
		UsefulArr[UsefulIndex]=OrigiArr[Random.Range(0, OrigiArr.length -1)];
		UsefulIndex += 1;
		makeUsefulCannonNo(UsefulIndex);
	} else if(UsefulIndex< OrigiArr.length) {
				
		tmpNo = OrigiArr[Random.Range(0, OrigiArr.length -1)];
		
		//if not same
		if(GetSameInUsefulCannonNoArr(UsefulIndex, tmpNo)==false) {
			UsefulArr[UsefulIndex]=tmpNo;
			UsefulIndex += 1;
						if(UsefulIndex>=OrigiArr.length){
				return;
			}
		}
		makeUsefulCannonNo(UsefulIndex);

	} else {
		print("Final here!");
	}
}

//if same return true;
function GetSameInUsefulCannonNoArr(iCnt: int, val: int): boolean {
	var rtn: boolean = false;
	for(var a : int = 0; a < iCnt; a++) {
		if(val==UsefulArr[a]) {
			rtn = true;
			break;
		}
	}
	return rtn;	
}

Thanks.

If this code is making Unity freeze, then the most likely cause is infinite recursion of the makeUsefulCannonNo function. I must admit I’m not really sure what this script is supposed to be doing, but I think using recursion is probably a very complicated way to go about it. :smile:

If you want to “shuffle” the array (that is to say randomly re-order it) then you might find this thread useful - it contains some code that can do that. Or are you aiming to choose a cannon at random and then avoid choosing it again immediately next time? If you can give a bit more detail, I can probably write some code to help you get started.