Search Unity

What about this function makes it an infinite loop?

Discussion in 'Scripting' started by glom1envisage0, Jan 26, 2012.

  1. glom1envisage0

    glom1envisage0

    Joined:
    Apr 3, 2011
    Posts:
    167
    Code (csharp):
    1. function CountSwitches()
    2. {
    3.     Counter = 0;
    4.     if(GameObject.Find("Switch prefab"))
    5.     do
    6.     {
    7.         var CurrentSwitch : GameObject = GameObject.Find("Switch prefab");
    8.         if((CurrentSwitch.GetComponent("SwitchScript").Go == true)(CurrentSwitch.GetComponent("SwitchScript").Stay == false))
    9.         {
    10.             NumberOfSwitchGos++;
    11.             CurrentSwitch.name = "SwitchGo"+(Counter + '');
    12.         }
    13.         else if((CurrentSwitch.GetComponent("SwitchScript").Go == false)(CurrentSwitch.GetComponent("SwitchScript").Stay == true))
    14.         {
    15.             NumberOfSwitchStays++;
    16.             CurrentSwitch.name = "SwitchStay"+(Counter + '');
    17.         }
    18.         else
    19.         {
    20.             Destroy(CurrentSwitch);
    21.         }
    22.         Counter++;
    23.     }
    24.     while(GameObject.Find("Switch prefab"));
    25.     Counter = 0;
    26. }
     
  2. glom1envisage0

    glom1envisage0

    Joined:
    Apr 3, 2011
    Posts:
    167
    Ok, I found A solution although I'm still not sure why destroying the object wouldn't prevent one of the same name to continually be found. I had to make the 'else' be that the object be renamed to something else. I just chose "Switch" leaving off the "prefab" and that worked.
     
  3. Marrrk

    Marrrk

    Joined:
    Mar 21, 2011
    Posts:
    1,032
    You can try DestroyImmediate instead of Destroy, as Destroy destroys the object at a later time than you might think.
     
  4. JamesLeeNZ

    JamesLeeNZ

    Joined:
    Nov 15, 2011
    Posts:
    5,616
  5. glom1envisage0

    glom1envisage0

    Joined:
    Apr 3, 2011
    Posts:
    167
    I call this script at start to track switches having been pressed and/or saved, but I'm guilty of using the "Find" shortcut in many other scripts in update. I usually get good framerates but the times I have slowdown don't necessarily seem justifiable considering the simplicity of objects I use.
     
  6. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    It's not really a shortcut in this case because you're Find()ing the same object over and over again. It's looping forever because Destroy does not happen immediately (hence the existence of DestroyImmediate). jlcnz's idea is better. Do a find all once and then iterate the result.