Search code examples
c#classdynamicunity-game-enginecreation

Creating objects at runtime


I'm working on an Unity3D application that basically fetches data from a server and attempts to create objects at runtime. When I'm trying to create this objects, via a constructor on some classes I have defined, I get the following error:

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

I can't move this to either Awake or Start since I need some feedback from my GUI (user credentials) before I run the mentioned code.

Any ideas/suggestions?


Solution

  • I was able to make it work. Here's a summary of what I did:

    1. Made the class instantiating the classes at run-time, referred as Creator, extend ScriptableObject. This allows to start the Creator class on demand using CreateInstance.
    2. Change the Creator class methods, variables and the class itself to static.
    3. When needed intantiate the Creatorclass via CreateInstance.
    4. Make sure to call the methods that do the class instantiating from Start, Awake or Update as appropriate. In my case it was Update.