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 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