Unity freeze by using Invoke

hi when i use invoke my unity editor will get frozen,
can someone help me with one alternative solution ?
thanks.

    void RandomTimer()
    {
        float rnd = Random.Range (minEventTime, maxEventTime);
        Invoke ("RandomItem", rnd);
    }

    void RandomItem()
    {
        bool isValid = false;
        InteractableObj ObjToChangeState;
        int count = 0;

        do
        {
            ObjToChangeState = AllObjs[Random.Range(0, AllObjs.Length)];
            if(!ObjToChangeState.isUsed)
            {
                ObjToChangeState.isUsed = true;
                ObjToChangeState.ChangeState(true);
                isValid = true;
            }
            count++;
        }
        while(!isValid);

        RandomTimer ();
    }

It make freeze if you never meet the condition.

add some debugs and a sanity check to break out if you get stuck.

(not actually useful code, but you get the drift.

int sanity = 0;

while(ourCondition == false && sanity < 1000){

//DO STUFF

sanity++

}

if(outCondition == false)
Debug.LogError("sanity check bail out");

Yep, has nothing to do with Invoke, you’re just getting stuck in your while loop if isValid never gets set to true, you never exit the loop.

how to fix that?

At your while loop check make it do this. You want to make sure that you have a way to exit the loop and since you have a counter already you can use that.

do
{
     ObjToChangeState = AllObjs[Random.Range(0, AllObjs.Length)];
     if(!ObjToChangeState.isUsed)
     {
           ObjToChangeState.isUsed = true;
           ObjToChangeState.ChangeState(true);
           isValid = true;
     }
     count++;
}
while(!isValid && count < AllObjs.Length);

So if all objects are used, your code will never exit the loop. Most of the time when unity freezes its because its entered an infinite loop.

If most objects are used, your code will take multiple cycles to exit the loop. Which is a waste of processing time. If your collection is large, this could easily cost you a frame or two.

I would strongly suggest using another collection which only contains the unused objects. Then randomly pick from there. If the collection is empty, then you can return an appropriate error.