- Home /
Serializable class with coroutines?
I have a class, which I want to make serializable
(to see some public variables in the inspector), but I also need to use Coroutines
in that class. To use Coroutines
in my class I must inherit it from MonoBehaviour. But then I can't use features of the serializable
class.
public class Act1HomeAwake : MonoBehaviour
{
public Act1_1HomeAwake act1_1HomeAwake;
public void StartAct1(int subActNumber)
{
switch(subActNumber)
{
case 1: act1_1HomeAwake.StartSubAct1_1(); break;
}
}
}
[System.Serializable]
public class Act1_1HomeAwake
{
// don't see this 2 variables in the inspector WITH inheriting from MonoBehaviour
public OpenCloseAnimation openCloseEyesScript;
public Text textTipsTasksComponent;
// WITHOUT inheriting from MonoBehaviour compiler don't understand this construction
StartCoroutine("OpenCloseEyesAnimation");
}
Answer by Bunny83 · Mar 27, 2016 at 11:40 PM
To use coroutines you don't need to derived your class from MonoBehaviour. You just need "some" MonoBehaviour instance to run your coroutine on. So the StartCoroutine call need to be done on a MonoBehaviour, but that could be a manager class. I made the CoroutineHelper class which represents such a manager. It's just a simple MonoBehaviour singleton. You can define coroutines (generators i.e. methods that return an IEnumerator) in any kind of class. You just need a MonoBehaviour to actually run the coroutine.
In your example you could simply do:
public class Act1HomeAwake : MonoBehaviour
{
public Act1_1HomeAwake act1_1HomeAwake;
public void StartAct1(int subActNumber)
{
switch(subActNumber)
{
// use StartCoroutine of this monobehaviour
case 1: StartCoroutine(act1_1HomeAwake.StartSubAct1_1()); break;
}
}
}
[System.Serializable]
public class Act1_1HomeAwake
{
public IEnumerator StartSubAct1_1()
{
// implement your coroutine here.
yield return null;
}
}
Another common solution would be to "pass" a MonoBehaviour instance to a method in a normal class. The normal class can use that reference to call StartCoroutine:
public class SomeMonoBehaviour : MonoBehaviour
{
public SomeClass obj;
void FooBar()
{
obj.DoSomething(this); // pass reference to this MonoBehaviour
}
}
[System.Serializable]
public class SomeClass
{
public void DoSomething(MonoBehaviour mb)
{
mb.StartCoroutine(SomeCoroutine()); // use the passed MonoBehaviour to start the coroutine.
}
IEnumerator SomeCoroutine()
{
yield return null;
}
}