How do I call a function containing a while loop, inside the update function?

Ok, so I’m trying to rotate my object, while a certain variable is not equal to another variable, this is the script I got.

private var go : boolean = true;
private var angle : float;
private var currAngleY : float;

function Update () {

if(Input.GetKeyDown("a")) {
		rotate("left");
	}
}

function rotate(direction : String) {
	Debug.Log("rotating");
	if(direction == "left") {
		if(go) {
			currAngleY = transform.eulerAngles.y - 90;
			go = false;
		}
		while(currAngleY <= transform.eulerAngles.y) {
			angle = Mathf.MoveTowardsAngle(transform.eulerAngles.y, currAngleY, 20 * Time.deltaTime);
			transform.eulerAngles = Vector3(0, angle, 0);
		}
		
	}

}

As soon as I try to run this, Unity just freezes and I have to hardreset it. Is there a way to make my object turn smoothly for only 90 degrees each time and then make it stop until the next input is given.

Yep, that is basically everything I do, except I do use MonoBehaviour to start the audio with OnTriggerEnter2D functions.

2 Answers

2

Update runs once every frame, so it’s clearly not suitable for that sort of thing. See here.

Thanks, this does what I want it to do. But it still needs some tweaking :)

Perhaps you can use If condition along with various flags to achieve what you want. Since update already does what you want your While loop to do.

For example,

if(conditionFlag)
{
//Your Rotate function
conditionFlag = false;
}

if(inputGiven)
{
conditionFlag = true;
}

I'll try this one too. Thanks for the reply.

No problem, i am glad that it solved the question. ^.^