I’ve been working on a game in Unity for a few weeks and I have been using the WWW object to make POST requests. Problem is that the WWW blocks the rendering thread so long running queries can make the game lag and stutter (alot).
To try to fix this I wanted to make a separate thread for all my network calls but since Unity is not thread safe I could not use the WWW request any more.
So I remade the request using the WebClient class, which was working great up until I tried it on windows phone. It appears this is not supported on WP. The reason for this is that twindows phone uses a slimmed down version of .net where as iOS and Android compile the code using .net mono.
Windows Phone 8 uses a different flavor of .NET called .NET for Windows Phone which is missing some of the types available on other platforms. You’ll have to either replace these types with different ones or implement them yourself.
If you try to use these methods on the WP8 you get (annoying) messages like these:
Error: method System.Byte System.Net.WebClient::UploadData(System.String,System.String,System.Byte)` doesn’t exist in target framework.
Error: method System.IO.Stream System.Net.HttpWebRequest::GetRequestStream() doesn’t exist in target framework.
Error: method System.Net.WebResponse System.Net.HttpWebRequest::GetResponse() doesn’t exist in target framework.
So after a bit of searching (and alot of trial and error) I arrived at the below code, which works on all platforms.
This is using WebRequests, according to the API for windows phone only certain methods are available so I could only use the async methods, but I’ve written the code so that it appears to be synchronous to the calling method which is what I wanted for my application (as I am calling it from a separate “networking thread” and not in the main thread).