function CountSwitches()
{
Counter = 0;
if(GameObject.Find("Switch prefab"))
do
{
var CurrentSwitch : GameObject = GameObject.Find("Switch prefab");
if((CurrentSwitch.GetComponent("SwitchScript").Go == true)(CurrentSwitch.GetComponent("SwitchScript").Stay == false))
{
NumberOfSwitchGos++;
CurrentSwitch.name = "SwitchGo"+(Counter + '');
}
else if((CurrentSwitch.GetComponent("SwitchScript").Go == false)(CurrentSwitch.GetComponent("SwitchScript").Stay == true))
{
NumberOfSwitchStays++;
CurrentSwitch.name = "SwitchStay"+(Counter + '');
}
else
{
Destroy(CurrentSwitch);
}
Counter++;
}
while(GameObject.Find("Switch prefab"));
Counter = 0;
}
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.
You can try DestroyImmediate instead of Destroy, as Destroy destroys the object at a later time than you might think.
I would be inclined to use findobjectsoftype and a loop…
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.
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.