When a node is created or removed, we need to send statistics to anything that is listening. To do this, we need a new method that will go through the scene and count how many planes and boxes we have and then send a message. Let's set this up by going through the following steps:
- In the WhackABox project, open the Game.cs file.
- Add a method called SendStats() anywhere in the class, as shown in the following code block:
private void SendStats()
{
var planes = scene.Children.OfType<PlaneNode>();
var boxCount = 0;
foreach (var plane in planes)
{
boxCount += plane.Children.Count(e => e.Name == "Box");
}
var stats = new GameStats()
{
NumberOfBoxes = boxCount,
NumberOfPlanes = planes.Count()
};
Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
{
Xamarin.Forms.MessagingCenter.Send(this, "stats_updated",
stats);
});
}
The method checks...