可序列化的类与协同程序?

时间:2016-03-27 20:17:41

标签: c# serialization unity3d

我有一个类,我想制作serializable(在检查器中查看一些公共变量),但我还需要在该类中使用Coroutines。要在我的班级中使用Coroutines,我必须从MonoBehaviour继承它。但后来我无法使用serializable类的功能。

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 // : MonoBehaviour
 {
     // 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");
 }

1 个答案:

答案 0 :(得分:1)

您需要序列化要显示的类:

[Serializable] // this is needed to show the object in Inspector
public class OpenCloseAnimation {}

[Serializable]
public class Act1_1HomeAwake 
{
    public OpenCloseAnimation openCloseEyesScript;
    public void CallCoroutine(MonoBehaviour mb)
    {
         mb.StartCoroutine(OpenCloseEyesAnimation());
    }
    public IEnumerator OpenCloseEyesAnimation(){ yield return null;}
}

但是想想也许你做错了。如果你班上需要一个协程,那么它可能就是MonoBehaviour。其他方法是从包含对象的MonoBehaviour开始协同程序。

public class MbClass : MonoBehaviour
{
    public Act1_1HomeAwake homeAwake;
    void Start(){
         // Considering you don't pass the MB in ctor anymore.
         this.homeAwake = new Act1_1HomeAwake();
         StartCoroutine(this.homeAwake.OpenCloseEyesAnimation());
    }
}