4
\$\begingroup\$

I have this game client which connects to the server and sends requests and getting responses.

I have created a separate thread for listening to the server. Based on the response from the server, I want make GameObjects.

But the problem is, the server response is taken into my game using a separate thread. And as far as I know, we cannot create game objects in unity in any other thread than Main Thread.

How to create game objects based on the server response?

I am new to c# and unity. Sorry if this is a silly question. I did some research on the topic and I couldn't find and answer. There were posts saying to use coroutines; but I can't quite understand them.

\$\endgroup\$
1
  • \$\begingroup\$ What kind of game objects are you loading? Is there a reason you cannot pre-load/pool them, and then Init them when you receive packets? \$\endgroup\$
    – jgallant
    Commented Nov 24, 2016 at 11:41

1 Answer 1

6
\$\begingroup\$

One of the options is using the Dispatcher pattern. The idea of this pattern is to create an object for each thread you want to invoke on(main thread in your case) which maintains list of delegates that is being polled and executed(e.g. in Update method). Since there is no implementation in Unity I am aware of, you either need to find Dispatcher implementation for Unity or implement it by yourself.

A very minimalist example

public class Dispatcher : MonoBehaviour
{
   protected Queue<Action> _pending = new Queue<Action>();

   void Update()
   {
      lock(_pending)
      {
         while(_pending.Count != 0) _pending.Dequeue().Invoke();
      }
   }

   public void Invoke(Action a)
   {
      lock (_pending) {_pending.Enqueue(a);}
   }
}

//spawning enemies from a new thread
public class Spawn: MonoBehaviour
{
    private Dispatcher _dispatcher;//init in Start() or editor

    void asyncSpawn()
    {
       for (int i = 0; i < _targetEnemyCount; i++)
       {
          Thread.Sleep(1000);
          _dispatcher.Invoke( () => spawnEnemy());
       }
    }

   void Start()
   {
      new Thread(() => asyncSpawn()).Start();
   }
}
\$\endgroup\$
1
  • \$\begingroup\$ Thank you very much. I implemented the Dispatcher pattern and now it works fine! :) \$\endgroup\$
    – john6667
    Commented Nov 24, 2016 at 13:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .