- Home /
"...can only be called from the main thread" - MultiThreading
Here's my code: http://pastebin.com/rXm7AtDw
I keep getting this error:
get_transform 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 am not familiar with multi-threading in Unity but as the error says, you cannot use a transform outside the main thread. You are trying to modify it in a secondary thread. That is probably to avoid conflicts between thread. Also, the Input you use Get$$anonymous$$ey will probably call many threads since you are unlikely to be pressing for only one frame. Use Get$$anonymous$$eyDown ins$$anonymous$$d. But that won't get you to use transform in a secondary thread.
But I really need to keep it running in background (multithreading), how can I do it?? :/
Why do you need to do a transform in a different thread?
Because I need to keep moving whole time, one by one, in background...
Answer by Henrik Poulsen · Feb 23, 2013 at 04:35 PM
The closest you can get to threading with the native unity3d functionality is [coroutines], since Unity isn't thread safe. If you know you need to do tasks that take a long time to compute you need to work around these limitations, if you feel you absolutely need to use multithreading. For example you might create a thread that calculates the data and then stores it and flags to the main thread that the data is ready to be processed and then you let the main thread set it.
However for the example you wrote I would probably do the following instead:
void Update () {
if(Input.GetKey (KeyCode.Space)) {
Cube.transform.position += transform.right;
}
}
Since GetKey() returns true as long as the key is pressed then it will do the offset every frame anyway. So there is no reason for threading in your situation.
[1]
[1]: http://docs.unity3d.com/Documentation/ScriptReference/index.Coroutines_26_Yield.html
Thanks for idea, I'll add code to the update() and use informations from thread :)
Your answer
Follow this Question
Related Questions
Job System without using the main thread 1 Answer
Unity Backgroundworker threading 2 Answers
Thread::CurrentThreadIsMainThread() 0 Answers
Threaded procedural animation 0 Answers
Error joining threads 0 Answers