【问题标题】:Serializable class with coroutines?带有协程的可序列化类?
【发布时间】:2016-03-27 20:17:41
【问题描述】:

我有一个类,我想创建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");
 }

【问题讨论】:

  • 您的代码不是有效的 C#?您正在尝试从任何类成员之外调用方法。

标签: c# serialization unity3d


【解决方案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());
    }
}

【讨论】:

    猜你喜欢
    • 2021-07-11
    • 2017-08-19
    • 1970-01-01
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    相关资源
    最近更新 更多