- Home /
How to execute method in main thread from another threads?
i see it hard to find any adequately answer on that.
i have a TcpClient that accept data in separate thread and should update gameobject state basing on received data.
first of all i can't call GameObject.Find("bla") from another thread. Well i though it's not a big problems and tried to use MethodInfo variable pointed on needed function, to execute it like this when received:
method_info.Invoke(this, new object[] { data }); //for weird reason it executes in current thread (not main)
ok... let's see then at this.Invoke("NeededFunction", 0); //what O_o? i can call it only in main thread? nice invoke
ok... let's see on delegates... err this does not contain InvokeRequred field and this is already a big problem
omg just how to access gameobjects from another threads?
Hi @kosmos, sorry for reviving this necro question, did you managed to solve this issue?, I'm right now facing the same problem and havent been able to find a solution :/
Answer by hrgchris · Feb 24, 2017 at 07:58 PM
Hi there
The correct approaches for this sort of thing vary depending on the task. You can not simply 'call a method on another thread' - you have to ask the other thread to call it.
I have found the most elegant approach in unity is to use the c# lock keyword to control access to a .net queue. I can add 'events' , which may be structures or delegates into my queue from a thread. Then on the main thread in an update function I can process the queue.
You can't access game objects and stuff from other threads - it's single threaded by design.
Chris
Hey @hrgchris, Thanks for the reply!
yeah, that's what I have seen (queue processing), but what happens when you need to execute it in the mainthread on an AssetPostProcessor function (I'm writing an importer) where you dont have a loop to process the queue :(?, how would you get around on that?
You can not simply "run code on another thread". A thread is a single sequencial execution unit. The code inside one thread is run in sequence. If you don't have something somewhere inside that sequence that runs code (like reading some method from a queue) you can't execute it on that thread.
The main loop of the main thread is controlled by Unity itself. Unity provides certain callbacks (like Update, ...) which allows you to put your code inside the main loop.
I think most AssetPostProcessor callbacks should actually be called from the main thread. The only exception might be "OnPostprocessAllAssets". If you need to queue things on the main thread from an editor script, you can use the generic update delegate of the EditorApplication class. That update is called about 100 times per second while the editor is active.
How you would implement that highly depends on your actual code and usage and does not belong here on this question. If you have a question, ask a seperate question and add more details.
That was basically what I was looking for, thanks! :) <3