0

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?

2
  • If you need credentials, why did you placed the logic into constructor? Move the code into custom method and call it when user performs required action and you have validated his inputs Commented Oct 27, 2014 at 15:42
  • Is in the constructor of the class I'm trying to instantiate, not constructor of a Scene, etc. Sorry for the confusion. Commented Oct 27, 2014 at 16:24

2 Answers 2

1

You can't create objects in your constructor or you will get that error. In fact, you should eschew constructors in general with Unity and favour Awake/Start/etc.

I don't know what you're doing, but there's no reason why you can't Instantiate() the object somewhere in your code, set it up properly on the next lines of code, and then let it's Awake()/Start() take place after that, letting it be fully initialized.

Sign up to request clarification or add additional context in comments.

3 Comments

Those classes are meant as data structures basically.
If they're just data structures, don't have them descend from MonoBehavior. Instead just make them free floating classes, make sure to put the [Serializeable] attribute tag on them, and reference them from a mono behaviour. You can use constructors as normal for that.
They were not descendants of MonoBehavior. See my answer for details on how I fixed it.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.