Problem Getting WaitForSeconds C# to Work

Hi All,

I am trying to get an object to spin one way, then pause for a random time, then spin back the other way. The following code does not pause. I get to the Debug.Log(“Hit”), but the pausing doesn’t occur. Any suggestions would be greatly appreciated!

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FlipDelay : MonoBehaviour {

	public float flipdelay;
	public float flipspeed;
	public float ctr = 0.0f;

	// Use this for initialization
	void Start () {
		ctr = -flipdelay;
	}
	
	// Update is called once per frame
	void Update () {
		StartCoroutine ("UpdatePosition");
	}

	IEnumerator UpdatePosition(){
		
		ctr += Time.deltaTime;
		//yield return new WaitForSeconds(5);
		if (ctr < 0){
			transform.Rotate(new Vector3(0.0f, flipspeed, 0.0f));
		} 
		if (ctr > 0){
			transform.Rotate(new Vector3(0.0f, -flipspeed, 0.0f));
		}
		if (ctr > flipdelay) {
			Debug.Log ("Hit");
			yield return new WaitForSeconds(Random.Range(1.0f, 5.0f));
			ctr = -flipdelay;
		}
	}

}

why would you put your call the co-routine from update? it will call it every frame. it won’t work with the delay.
what you need is:

float rotation_speed = 0;
start(){
  StartCoroutine (setRotationSpeeds());
}

update(){
  //rotate by rotation_speed and time.deltatime
}

IEnumerator setRotationSpeeds(){
   rotation_speed  = some positive speed;
   yield return new waitForSeconds(positive spin time);
   rotation_speed  = 0;
   yield return new waitForSeconds(delay time);
   rotation_speed  = some negative speed;
}

your using StartCoroutine inside update which calls your Coroutine in every frame which is the reason your code doesnt work , if you want the pause to happen and you want it to happen periodically you use this code :

public class FlipDelay : MonoBehaviour {

		public float flipdelay;
		public float flipspeed;
		public float ctr = 0.0f;

		// Use this for initialization
		void Start () 
		{
			ctr = -flipdelay;
			InvokeRepeating("CallCor",0,1.5f);
		}

		void CallCor()
		{
			StartCoroutine(UpdatePosition());
		} 


		IEnumerator UpdatePosition(){

			ctr += Time.deltaTime;
			//yield return new WaitForSeconds(5);
			if (ctr < 0){
				transform.Rotate(new Vector3(0.0f, flipspeed, 0.0f));
			} 
			if (ctr > 0){
				transform.Rotate(new Vector3(0.0f, -flipspeed, 0.0f));
			}
			if (ctr > flipdelay) {
				Debug.Log ("Hit");
				yield return new WaitForSeconds(Random.Range(1.0f, 5.0f));
				ctr = -flipdelay;
			}
		}

	}