在运行时创建对象

时间:2014-10-27 15:32:12

标签: 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 in the constructor or field initializers, instead move initialization code to the Awake or Start function

我无法将其移至Awake或Start,因为在运行上述代码之前,我需要从GUI(用户凭据)获得一些反馈。

有任何想法/建议吗?

2 个答案:

答案 0 :(得分:1)

您无法在构造函数中创建对象,否则您将收到该错误。事实上,你应该避免使用Unity一般的构造函数,并支持Awake / Start / etc。

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

答案 1 :(得分:0)

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

  1. 让类在运行时实例化类,称为Creator,扩展ScriptableObject。这允许使用CreateInstance按需启动Creator类。
  2. 将Creator类方法,变量和类本身更改为static。
  3. 需要时通过CreateInstance来填充Creatorclass。
  4. 确保根据需要调用从Start,Awake或Update实例化类的方法。就我而言,它是更新。