Hello,
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
}
else
{
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 );
break;
}
};
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.