Why does this script freeze Unity

Hi everybody

I wrote this script and tested it. Unity did not display an error, so I thought it was safe. I attached it to a empty GameObject and added a trigger. But when my player character, tagged “Player” enters the trigger, Unity completely freezes and I have to shut it down. I expect a problem with the for loop. I want this script to check all aggro variables, which are being set by another script, and find the GameObject which holds the same position in the first list which has the highest aggro. I want this to be done all the time until another script destroys the GameObject it’s attached to.

import System.Collections.Generic;

var players : List.<GameObject> = new List.<GameObject>();
var aggros : List.<int> = new List.<int>();
var highestaggro : int = -1;
var checkednumber : int = 0;
var target : GameObject = null;

function OnTriggerEnter (trigger : Collider){
if(trigger.tag == "Player"){
if (target == null){
AggroCheck ();

function AggroCheck (){
for (i = 0; i<1; ){
if (checkednumber == aggros.Count){
checkednumber = 0;
if (aggros[checkednumber] > highestaggro){
target = players[checkednumber];
highestaggro = aggros[checkednumber];

Because i is always < 1 and you never exit the for-loop. Correct syntax is:

for (i = 0; i < 1; i++ ){

I believe you are missing some basic programming concepts.

It is like delstrega said.

for (i = 0; i<1; ){ // Freeze!

will loop forever. An the main thread will never return to the unity backend. - You are never allowed to block the main thread forever. (Well you are allowed, but it will freeze).

If you want to have anything checked as often as possible put it into the Update() function. It will be called every time a screen is rendered. Another approach (if every lets say 100ms is enought) would be some kind of Coroutine or Invoke implementation.

Answer to your comment:

Well of course you can do it with a for loop, but that loop should not run forever.

I do my stuff in C# mostly, so I try to give my best in javascript:

   var length : int = myArray.length;
   var maxValue;
   var maxValueIndex : int = -1;
   if(length > 0) {
      maxValue = myArray[0];
      maxValueIndex = 0;
      for(var i : int = 0; i < length; i++) {
         if(myArray *> maxValue){*

maxValue = myArray*;*
maxValueIndex = i;
// maxValue and maxValueIndex are valid if maxValueIndex >= 0
Now you can feel free too optimize it. If this is called very often, you can use member variables to trade some memory for speed.