Tuesday, 28 October 2014

Using async and await for Asynchronous calls in C# and VB

We are going to user asynchronous call to get length of web that we requested.

Download : C# or VB

Create new WPF project.



Add textbox and button.


Rename button to runAsyncButton and textbox to resultsWindow.
You can either do that  by adding x:Name property for each element, or click an element and get the properties and change name.
<Button x:Name="runAsyncButton" ... />
<TextBox x:Name="resultsWindow" .../>

Double click on button and click method is generated.

Xaml code for grid should looks similar:



Add this to your click method :
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
   resultsWindow.Clear();
   resultsWindow.Text += "Asynchronous call started";
   runAsyncButton.IsEnabled = false;
   runAsyncButton.Content = "Running...";
   await SumPageSizesAsync();
   runAsyncButton.IsEnabled = true;

   runAsyncButton.Content = "Run";
   resultsWindow.Text += "\n Asynchronous call finished";
}


As you can see method needs to have async keyword to perform as an asynchronous call.
Await keyword on SumPageSizesAsync method works in pair with async and tells method to wait before continuing if method is still being executed. 

We have to write SumPageSizesAsync method:


private async Task SumPageSizesAsync()
{
   List<string> urlList = SetUpURLList();

   foreach(var url in urlList)
   {
      // return contents as a byte array
      Byte[] urlContent = await GetURLContentsAsync(url);

      DisplayResults(url, urlContent);
   }

}


To populate list with url addresses:



private List<string> SetUpURLList()
{
   List<string> urls = new List<string>() { 

   "http://msdn.microsoft.com/library/windows/apps/br211380.aspx",
   "http://msdn.microsoft.com",
   "http://msdn.microsoft.com/en-us/library/hh290136.aspx"
};

return urls;
}


Now we have to write the core method - GetURLContentsAsync.


private async Task<byte> GetURLContentsAsync(string url)
{
   MemoryStream content = new MemoryStream();

   HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);

   // Send request and wait for response

   Task<webresponse> responseTask = webReq.GetResponseAsync();

   using (WebResponse response = await responseTask)
   {
      using (Stream responseStream = response.GetResponseStream())
      {
         await responseStream.CopyToAsync(content);
      }
   }
   return content.ToArray();
}


Final method is DisplayResults.

private void DisplayResults(string url, Byte[] content)
{    
   var bytes = content.Length;  
   resultsWindow.Text += string.Format("\n {0} {1}", url, bytes); 
} 


Run the program.




Saturday, 18 October 2014

Unity 3d frozes when loading or closing project

Occasionally I encounter issue which prevent me from closing Unity 3d or loading new project. After googling I found out that there is a process abd.exe running in the background that cause Unity to behave oddly. If your project is set up to Android project you are likely to have this process running.
More info about adb process can be found here : http://www.file.net/process/adb.exe.html

Simply saying adb is one of the Android SDK processes.

Shut all adb process from task manager panel and that should fix the problem.


Thursday, 9 October 2014

2 Simple rules to improve performance in Unity 3d when writing Scripts

So you created beautiful looking game that run 90 fps on your machine and then your exported it to mobile device and your excitement disappeared once you opened it -slow, lag, unplayable. If you haven't experienced that either you are genius talented video game designer or your game is not very resource demanding. I have been in this situation and my solution was to carefully start optimizing game so it will run much smoother and users that still have few years old devices(like me) can enjoy the game. This is not holy grail unity tutorial, but it definitely helps me in many occasions.

It is very important to think about performance in an early stage when creating video game/app using unity game engine. Some bad design can cause headache in the future, especially when your game gets bigger and more resource demanding.

Of course writing optimised script is not the only way to improve performance in unity games. Another way is to reuse materials, avoid using transparent shader on mobile devices etc.

Due to my experience I found out that those 2 very simple tricks works well.

1. Cache an object when using it often (especially in Update function).


Example.

   void Start ()

   {

       double totalA = 0;

       double totalB = 0;

       int counter = 1000000;

       // Caching our transform

       Transform tr = GetComponent();

       var currentTime = DateTime.Now;

       // First test with cache

       for (int i = 0; i < counter;i++)

       {

           Vector3 vec = tr.position;

           vec.x = 10;

           tr.position = vec;

       }

       totalA = (DateTime.Now - currentTime).TotalMilliseconds;

       // Second test with no cache

       currentTime = DateTime.Now;

       for (int k = 0; k < counter; k++)

       {

           Vector3 vec = transform.position;

           vec.x = 10;

           transform.position = vec;

       }  

       totalB = (DateTime.Now - currentTime).TotalMilliseconds;

       print (totalA);

       print (totalB);

   }

1st loop will perform faster.

2. Use static variables rather than public.


 Static variable belongs to an class rather than object, therefore it is faster to access. Careful as if the same class is being used for the same prefabs(eg enemy), if you kill one enemy, all of them will be dead.  If that approach at least helped you to get extra fps let me know!