Cannot get player to spawn


I’ve been trying to get player to spawn upon joining a match by broadcasting a message to all presences then the client would call a method to spawn a character into the scene.

The problem is that I have separated methods (authentication, connecting to server, joining a match, etc…) and these methods return a Task (since I cannot “await void”) and because of that (as far as my understanding) these methods run in a background thread and therefore whenever I call a method that runs in the main thread i.g: “SpawnCharacter” Unity errors an exception “get_transform can only be called from the main thread.”

here’s how a “SpawnCharacter” method look like:

public void SpawnCharacter(bool localPlayer)
    if (localPlayer)
        Instantiate(playerPrefab, transform); // receives input locally
        Instantiate(characterPrefab, transform); // receives input virtually

and this is the method that I use to connect client’s to the server:

public async Task ConnectToServerAsync()
    socket = client.NewSocket();
    socket.Connected += () => Debug.Log("Connected to server.");
    socket.Closed += () => Debug.Log("Disconnected from server.");
    socket.ReceivedMatchState += newState =>
        switch (newState.OpCode)
            case (int) OP_CODES.SPAWN:
                gameController.SpawnCharacter( newState.UserPresence.UserId == session.UserId );
    await socket.ConnectAsync(session);

I’m not even sure what’s the actual issue here but if you know how to fix my problem then please do tell me.

@izhvnter Hi! This has been discussed on the forums a few times before. Unity restricts certain operations to being run on the main thread only.

The standard solution is to use a main thread dispatch pattern, like this post describes.

1 Like