Using a coroutine to spin an object after a delay
IEnumerator spinnyspin ()
{
yield return new WaitForSeconds (1);
while (true)
{
transform.Rotate (new Vector3 (15, 30, 45) * Time.deltaTime);
}
}
void Start ()
{
StartCoroutine (spinnyspin ());
}
}
I am trying to spin an object after a short delay but it won't work. I can rotate using a co routine but the permanent spin after a delay won't and I can't use a co routine in an update what do?
Answer by Pengocat · Jan 31, 2017 at 01:16 PM
The while loop will loop forever and never allow any other code to continue. Therefore you need to yield inside the while loop so that the execution outside this script can continue and return in the next frame. As a tip you can make the Start method a Coroutine then you don't need to start it manually. All you need is this code:
// Start is called just before any of the Update methods is called the first time
IEnumerator Start()
{
yield return new WaitForSeconds(1f);
while (true)
{
transform.Rotate(new Vector3(15, 30, 45) * Time.deltaTime);
yield return null;
}
}
It is a common misconception that Coroutines run in another thread but they do not. Every script communicating with the Unity Engine runs in a single thread.
Your answer
Follow this Question
Related Questions
Coroutine or While loop that you can reset/add time too? 0 Answers
Unity Freezing after for loop 1 Answer
My coroutine won't work 0 Answers
Coroutine only works one way 1 Answer
Insantiate Loop Issue 0 Answers