What part of my While Loop is causing the game to freeze? (C#)

Hey guys, before I ask my question, I will give you guys a quick overview of what I am doing and what I want to achieve. I am working on a Real-Time Strategy game, and currently have scripts to make a GUI with buttons to spawn units, and a GUI box that includes labels telling you what your current gold is, gold per minute, total workers, etc. I am relatively new to Unity3D, and C# scripting in general, but I have basic knowledge of Java, C++, Python, Blitz, and more. When my units spawn, they are instantiated at empty GameObjects that I call Team1WarriorSpawn, Team1ArcherSpawn, and so on. When they spawn, they do nothing but stand at their respective spawn points.

Therefore, I need a script to move the newly instantiated units to the other team’s castle. I already have tags set up that inform the units of what team they are on, what team to attack, and things like that. I set up the following While Loop inside a method called AttackEnemyCastle()…

    public void AttackEnemyCastle(){
     float distanceFromCastle = Vector3.Distance(attackPoint.transform.position, unit.transform.position);
     
     while(distanceFromCastle > 1){
     
     Debug.Log("Moving towards enemy castle.");
     //look at target
     unit.transform.rotation = Quaternion.Slerp(unit.transform.rotation,Quaternion.LookRotation(attackPoint.position - unit.transform.position),rotationSpeed * Time.deltaTime); 
     
     Debug.DrawLine(unit.transform.position, attackPoint.position, Color.yellow);
     
     //move towards target
     unit.transform.position += unit.transform.forward * moveSpeed * Time.deltaTime;
    }
}

After I hit play with the Script attached to the team’s GameSettings (GameObject I use for variables like currentGold, currentWorkers, unitCosts, etc.), the game runs fine, without a hitch. But as soon as I click the button to spawn a warrior, or archer for that matter, the game instantly freezes, and I have to force quit out of Unity. Any help would be appreciated, I hope I was descriptive enough without overdoing anything. Thanks in advance for your answers!

It’s freezing because if distanceFromCastle is greater than 1, it goes into an infinite loop…since you never set distanceFromCastle less than or equal to 1 at any point in the loop, it can never exit the loop in order to do anything else.

Eric is right, a coroutine would work for this issue.

Another alternative is to consider taking care of the unit’s movement in the unit script’s update. In general you want to handle things like movement or other things that happen over time in an update. That’s why they exist.