Why is my healing code causing unity to freeze and crash?

Heya. I’m new to unity (been using it for about a week) and have an issue with some code. This seems to make unity crash or just freeze up. I just want the current health variable to increase per second as long as you are “healthy”. Help is appreciated if its just that my code is not optimal.

var maxHealth : int = 1000;
var curHealth : int = 1000;
var healthy : boolean = true;

var nextActionTime : float = 0.0;
var period : float = 0.1;

while (healthy){
	Heal();
}

function Heal(){
	if (Time.time > nextActionTime ) {
    	nextActionTime += period;
			if(curHealth < maxHealth){
				curHealth += 1;
			}
	}
}

The base issue is that you have no yield here, so once your code goes into the while loop, it never returns control to the rest of your program. There are other issues as well. Try this instead:

#pragma strict

var maxHealth : int = 1000;
var curHealth : int = 1000;
var healthy : boolean = true;

var period : float = 0.1;
 
function Start() {
	InvokeRepeating("Heal", period, period);
}
 
function Heal(){
         if(healthy && curHealth < maxHealth){
          curHealth += 1;
         }
}

Note with a period of 0.1, you will get approximately 10 points per second increase.