- Home /
Coroutine not working ? possible errors ?
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ChangeScene : MonoBehaviour {
public Animator anim;
void Start()
{
anim = gameObject.GetComponent<Animator> ();
}
public void ChangeToScene(string sceneToChange)
{
StartCoroutine (LodingScene());
Application.LoadLevel(sceneToChange);
}
IEnumerator LodingScene()
{
anim.SetBool ("start", true);
Debug.Log ("In the Coroutine");
yield return new WaitForSeconds (0.3f);
}
}
this is my script which is connected to a button in new canvas UI. and i am trying to make one one animation run as soon as button is pressed
But the scene changes instantly
What can be the possible errors ?
If you are trying to add a delay—before the load operation begins, but during the animation—try moving
Application.LoadLevel(sceneToChange);
just after
yield return new WaitForSeconds (0.3f);
I did not get you Do you mean place Application.LoadLevel(sceneToChange); inside the Coroutine ??
if so, then how can i pass the 'sceneToChange' to LodingScene() Coroutine
I guess i can not call a Coroutine from a UI canvas button
Whohhh !!! it worked :D Thanks @Victory Dan Greene
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class ChangeScene : $$anonymous$$onoBehaviour {
public Animator anim;
void Start()
{
GameObject comp = GameObject.FindGameObjectWithTag ("retro");
anim = comp.GetComponent<Animator>();
}
public void ChangeToScene(string sceneToChange)
{
StartCoroutine (LodingScene(sceneToChange));
}
IEnumerator LodingScene(string sceneToChange)
{
anim.SetBool ("start", true);
Debug.Log ("In the Coroutine");
yield return new WaitForSeconds (5f);
Application.LoadLevel(sceneToChange);
}
}
exactly what you told me to do Thanks ^_^ much Appreciated !!
Answer by DanSuperGP · Jan 07, 2015 at 06:23 PM
You are starting the coroutine and then instantly changing scenes.
public void ChangeToScene(string sceneToChange)
{
StartCoroutine (LodingScene());
Application.LoadLevel(sceneToChange);
}
This isn't going to wait for the coroutine to finish. It starts the coroutine and then immediately goes on to the next line of code.
If you want to delay the scene load, you need to put the LoadLevel call in the Coroutine.
public class ChangeScene : MonoBehaviour {
public Animator anim;
private bool coroutineHasStarted = false;
void Start()
{
anim = gameObject.GetComponent<Animator> ();
}
public void ChangeToScene(string sceneToChange)
{
if( ! coroutineHasStarted)
{
coroutineHasStarted = true;
StartCoroutine (LodingScene(sceneToChange));
}
}
IEnumerator LodingScene(string sceneToChange)
{
anim.SetBool ("start", true);
Debug.Log ("In the Coroutine");
yield return new WaitForSeconds (0.3f);
Application.LoadLevel(sceneToChange);
}
}