C# - problem controlling a function with a toggle

Hi there,
I’m having some trouble with a toggle button =). What I want to do with the button is pretty simple (at least I thought). When toggled on, it triggers a function in the Spawn scriptfile. The function should run until the toggle is triggered again. Here is my code so far, that unfortunately crashes unity on execution:

GUI_dev Script

void Update()
    {
        if (spawn != spawnToggle)
        {
            if (spawn == true)
            {
                action = "spawn";
                playerHQ.spawnUnit();
            }
            else
            {
                action = "none";
            }

            spawnToggle = spawn;
        }
    }

void OnGUI ()
    {
        spawn = (GUI.Toggle(new Rect(10, 10, 150, 50), spawn, "Spawn"));
        
    }

Spawn Script

public static void spawnUnit(GameObject player, GameObject unit)
    {
        while (GUI_dev.action == "spawn")
        {
            //Select place to spawn
        }
    }

I know that this is most likely a programming issue (I just got started with C#), but I hope somebody can give me a hint how to do this in a correct, elegant way, or at least point me to a website with a solution =).

Thanks in advance,

Thomas

PS: Can anybody recommend the “Beginning C#” tutorials in the Unity Creative magazine?

My guess is this is the portion of the code that is “crashing” Unity:

     while (GUI_dev.action == "spawn") 
        { 
            //Select place to spawn 
        }

It’s not actually crashing, but it stays in that while holding all other processing.

You could use this code

if (GUI_dev.action == "spawn") {
    // spawn code...
}

inside an Update function.

As you may notice, I replaced the “while” with an “if”. And putting it inside an Update function will make it to be execute every frame.

Thanks, that seems like a practicable solution. The reason I wanted to put everything into a function is that a) for readability and less cluttered code and b) don’t do anything OnUpdate if it’s not necessary. So maybe there is a way to do it inside that function?

There’s no other way I know of, if you want your code be executed every frame.

You could call that function from the Update for readability. And do the “if” check on that function.