Basically, that’s all you need to know. I want to find out if there’s an elegant way of doing it
Nope. Awake, Start, Update, etc.
These are the functions that run your code. There’s no way to run code outside of these main functions. I don’t see why you would want to however, perhaps with more details we could solve your problem.
I’ve got an open TCP
connection going on in that other thread and I have to create an Instance of a an object according to the information in a message completely independently from the Update(). I tried putting a timeout on Recieve() in the main thread but it won’t work.
Try coroutines, they can wait or progress your code at any point when needed.
I have implemented a TCP pipeline, that seems to do exactly what you are trying to do. I receive information about the creation of GameObjects with the help of json serialized scene graphs. My pipeline works as follows:
I.) send scene description over TCP connection
II.) threaded client handler instanced by the server receives message outside main thread
III.) Event sends message to JsonParser which queues it inside a buffer
IV.) inside Update() function of the JsonParser, I parse and create GameObjects based on the stuff stored in the buffer
(after reading, I obviously remove the parsed messages from the buffer)
I guess, there would be other designs that would also work. The trick always seems to be storing asynchronious gathered information and using it when you are inside the main thread next.
I Hope that helps!
public void SendMessageOnMainthread( string message )
{
actionQueue.Enqueue(() =>
{
SendMessage(message);
} );
}
void Update()
{
if (actionQueue.Count > 0)
{
actionQueue.Dequeue()();
}
}
I use MQTT protocol. But I can’t instantiate object outside main thread.
From your outside thread, tell the main thread to instantiate the object. Since .net 4.x and later C# language support was added, I prefer using a ConcurrentQueue for this type of thing.