- Home /
Can't access to Time.time in callback method AsyncCallback
Hi,
I'm currently having a problem in my game when it connects to my server (I'm coding in C#).
When I try to log in the server, my protocol open a new TcpClient and as soon as my client is logged in, the method OnConnect is called (by creating a new instance of AsyncCallback).
socketConnection = new TcpClient();
socketConnection.BeginConnect(host, port, new AsyncCallback(OnConnect), auth);
If I try to use Time.time in my method OnConnect, the game crashes by just giving me the stacktrace but nothing else :
UnityEngine.Time:get_time()
SimpleClient:OnConnect(IAsyncResult) (at Assets\Scripts\Network\SimpleClient.cs:109)
System.Net.Sockets.SocketAsyncResult:Complete()
System.Net.Sockets.Worker:Connect()
Here is the code of my OnConnect method :
public void OnConnect(IAsyncResult asr)
{
Debug.Log(Time.time);
}
Any idea on what's going on ? Any help would be greatly appreciated.
Thanks.
Answer by Mike 3 · Mar 17, 2011 at 02:18 PM
Unity isn't threadsafe, so using most of the API from a thread will cause it to crash, throw exceptions or just do weird stuff
What you generally need to do is put your results into a queue of some sort and parse them from Update, or another unity synchronized function