C# 在运行时创建对象

C# 在运行时创建对象,c#,class,dynamic,unity3d,creation,C#,Class,Dynamic,Unity3d,Creation,我正在开发一个Unity3D应用程序,它基本上从服务器获取数据,并尝试在运行时创建对象。当我试图通过已定义的某些类上的构造函数创建此对象时,出现以下错误: get_name can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function

我正在开发一个Unity3D应用程序,它基本上从服务器获取数据,并尝试在运行时创建对象。当我试图通过已定义的某些类上的构造函数创建此对象时,出现以下错误:

get_name can only be called from the main thread.
Constructors and field initializers will be executed from the loading thread when loading a scene.
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function
我无法将其移动到唤醒或启动,因为在运行上述代码之前,我需要GUI(用户凭据)的一些反馈


有什么想法/建议吗?

您不能在构造函数中创建对象,否则会出现错误。事实上,一般来说,您应该避免使用统一的构造函数,并支持Awake/Start/etc


我不知道你在做什么,但是你没有理由不能在代码中的某个地方实例化()对象,在下一行代码中正确设置它,然后让它唤醒()/Start(),让它完全初始化。

我能够让它工作。以下是我所做工作的总结:

  • 使在运行时实例化类的类(称为Creator)扩展。这允许使用按需启动Creator类
  • 将Creator类方法、变量和类本身更改为static
  • 需要时,通过以下方式通知Creator类
  • 确保根据需要从Start、Awake或Update调用进行类实例化的方法。在我的情况下,这是更新

  • 如果您需要凭证,为什么要将逻辑放入构造函数中?将代码移到自定义方法中,并在用户执行所需操作时调用它,并且您已经在我尝试实例化的类的构造函数中验证了他的输入,而不是场景的构造函数,等等。很抱歉造成混淆。这些类基本上是指数据结构。如果它们只是数据结构,不要让他们从单一行为中堕落。相反,只需让它们成为自由浮动类,确保将[Serializable]属性标记放在它们上面,并从mono行为引用它们。你可以像平常一样使用构造函数,它们不是MonoBehavior的后代。查看我的答案,了解我如何修复它的详细信息。