- Home /
C# IEnumerator Function Inheritance Dilemma
I'm switching over from using the Resources folder to AssetBundles in order to save memory on the iPhone. I have a Manager class that's loading these bundles at the start of the scene, but it inherits from two other classes behave similarly. I need to keep their functionality intact. How exactly would I call the functions from these classes higher in the hierarchy? I've tried just using base.Function, but it isn't working since the functions need to return IEnumerators to load WWW.
So, my question is this. Is there a way to load an AssetBundle without making the function IEnumerator and if not, is there a way for an IEnumerator function to call the base version of itself without starting another asynchronous process?
Answer by luizgpa · Dec 02, 2011 at 03:28 AM
To call a coroutine inside a coroutine, and you want to wait for the first one to finish, you should use the following syntax:
yield return StartCoroutine(CoroutineFunction());
If you don't need to wait you should use only:
StartCoroutine(CoroutineFunction());
I don't know if I understood your class organization correctly, but the same applies if the coroutine is an virtual method from a base class. Eg:
public abstract class A : MonoBehaviour
{
protected virtual IEnumerator Load()
{
print("A: load something");
yield return new WaitForSeconds(1.5f);
print("A: finished");
}
}
public class B : A
{
protected override IEnumerator Load()
{
print("B: started");
yield return StartCoroutine(base.Load());
print("B: load more stuff");
yield return new WaitForSeconds(1);
print("B: finished");
}
void Start()
{
StartCoroutine(Load());
}
}
In the example B.Load will call A.Load and wait for it to finish before continue the execution. The console will show:
B: started
A: load something
A: finished
B: load more stuff
B: finished
what if non $$anonymous$$onoBehaviour class and cant call StartCoroutine???
You have to have an active gameobject to run a coroutine. You can usually do something like: gameobject.StartCoroutine(Load()); where gameobject is a reference to an active gamebject in the scene.