Add Google Analytics to your project

Hey everyone,

Just wanted to share this class which I have used a while now. It allows you to track events and “levels” (normally pages ;)) at Google Analytics.

Only thing you need is a Google Analytics account and a verified domain. This is just to get the tracking activated, just a one time process.

The only thing you have to do is to set the account id and optionally the (request) domain in the singleton, and then it’s just a one time function call per event. Like logins, registration, etc!

Download the code on my old-dated but still quite useful website :wink:.

http://www.persistentrealities.com/code/

Example:

Hey that’s a novel use for Analytic’s.
Well done!

/tip hat

This is excellent! I’ve been thinking about event tracking in the game and can’t wait to give this a try. Thanks!

Kudos to you, Sir. This is useful as hell!

I did forget to mention that it might take a few hours before the data shows up on your site. Especially if you just added a new domain. :).

So Google and Unity already has a good relationship what with the webplayer being integrated with Chrome. You know, this is the kind of thing that the two should look into themselves and promote - just showing how powerful it can be on the web for game developers and marketing firms/departments.

a small technical note: I think you should remove the last line from the LogEvent function… the “while ( w.isDone == false ) {};” will cause a lag in program flow - and is quite unneccessary.

Ah, I likely left it there because of debugging reasons, since I have often looked at the response data. I will remove it later today.

I adapted the system for .Net 1.1 (iPhone-compatible) and put in an asynchronous call of the LogEvent() function (put it in a coroutine to make it even faster and completely without lag).

Almar, you interested in the changed code?

Oh, on another note: could you give some examples for ways to use LogEvent()? Analytics tells me, it’s receiving data, but it does not show any counts. Any idea how to fix that?

Hi azeitler,

This is what I used to make sure the code really worked before uploading ;).

GoogleAnalyticsHelper.Instance.Settings(“UA-(yourid)”, “127.0.0.1”); /// (or possibly domain which hosts the “activated” domain)
GoogleAnalyticsHelper.Instance.LogEvent(“Server”, “myGame”, “Startup”, “”,0); // The latter arguments can be used for values and prices for example. (“event value”) at GA
GoogleAnalyticsHelper.Instance.LogPage(“DefaultLevel”); /// Actually the current level is used automatically if an empty string is passed

Does this work for standalone games or just web players?

@azeitler

Are you sharing your iPhone adapted code? That would be very cool to test it in a project.

It should work fine on both, since I am not using any custom DLL’s.

Here is my version of the code. I did some improvements on the memory footprint, removed generics and turned all functionality into static functions.

I dropped the async-Coroutine as it does not bring any performance-advantage after all, don’t know where I got the idea that it would.

using UnityEngine;
using System.Collections;

/// Google analytics class v 1.1
/// v1.0 (c) by Almar Joling 
/// E-mail: [email]unitydev@persistentrealities.com[/email]
/// Website: [url]http://www.persistentrealities.com[/url]

/// Performs a google analytics request with given  parameters
/// Important: account id and domain id are required.
/// Make sure that your site is verified, so that tracking is enabled! (it needs a file to be placed somewhere in a directory online)

/// Example usage:
/// One time initialize:
/// Use a different hostname if you like.
/// GoogleAnalyticsHelper.Instance.Settings("UA-yourid", "127.0.0.1");

/// Then, for an "event":
///  GoogleAnalyticsHelper.Instance.LogEvent("levelname", "pickups", "pickupname", "optionallabel", optionalvalue);

/// For a "page" (like loading a level?)
/// GoogleAnalyticsHelper.Instance.LogPage("Mainscreen");		

/// If you made any improvements please let me know :).



public sealed class GoogleAnalyticsHelper
{
	private static string accountid;
	private static string domain;
	
	private static readonly GoogleAnalyticsHelper instance = new GoogleAnalyticsHelper();		
	
	/// Init class with given site id and domain name
	public static void Settings(string p_accountid, string p_domain)
	{
		domain = p_domain;
		accountid = p_accountid;
	}


	public static void LogPage(string page)
	{
		LogEvent(page, "","","", 0);
	}

	/// Perform a log call, if only page is specified, a page visit will be tracked
	/// With category, action, and optionally opt_label and opt_value, there will be an event added instead
	/// Note that the statistics can take up to 24h before showing up at your Google Analytics account!
	private static Hashtable requestParams = new Hashtable();
	public static void LogEvent(string page, string category, string action, string opt_label, int opt_value)
	{
		if (domain.Length == 0)
		{
			Debug.Log("GoogleAnalytics settings not set!");
			return;
		}
		
		long utCookie = Random.Range(10000000,99999999);
		long utRandom = Random.Range(1000000000,2000000000);
		long utToday = GetEpochTime();
		string encoded_equals = "%3D";
		string encoded_separator = "%7C";
		
		string _utma = utCookie + "." + utRandom + "." + utToday + "." + utToday + "." + utToday + ".2" + [url]WWW.EscapeURL[/url] (";") + [url]WWW.EscapeURL[/url] ("+");
		string cookieUTMZstr = "utmcsr" + encoded_equals + "(direct)" + encoded_separator + "utmccn"+ encoded_equals +"(direct)" + encoded_separator + "utmcmd" + encoded_equals + "(none)" + [url]WWW.EscapeURL[/url] (";");
		
		string _utmz = utCookie + "." + utToday + "2.2.2." + cookieUTMZstr;
		
		/// If no page was given, use levelname:
		if (page.Length == 0)
		{
			page = Application.loadedLevelName;
		}

		requestParams.Clear();
		requestParams.Add("utmwv", "4.6.5");			
		requestParams.Add("utmn", utRandom.ToString());	
		requestParams.Add("utmhn", WWW.EscapeURL(domain));
		requestParams.Add("utmcs", "ISO-8859-1");
		requestParams.Add("utmsr", Screen.currentResolution.width.ToString() + "x" + Screen.currentResolution.height.ToString());	
		
		requestParams.Add("utmsc", "24-bit");
		requestParams.Add("utmul", "nl");	
		requestParams.Add("utmje", "0");		
		requestParams.Add("utmfl", "-");		
		requestParams.Add("utmdt", WWW.EscapeURL(page));
		requestParams.Add("utmhid", utRandom.ToString());				
		requestParams.Add("utmr", "-");				
		requestParams.Add("utmp", page);	
		requestParams.Add("utmac", accountid);		
		requestParams.Add("utmcc", "__utma" + encoded_equals +_utma + "__utmz" + encoded_equals + _utmz );
		
		
		/// Add event if available:
		if (category.Length > 0  action.Length > 0)
		{
			string eventparams = "5(" + category + "*" + action;
			
			if (opt_label.Length > 0)
			{
				eventparams += "*" + opt_label + ")(" + opt_value.ToString() + ")";
			
			} else {
						
				eventparams += ")";
			}
			
			requestParams.Add("utme", eventparams);
			requestParams.Add("utmt", "event");
		}
		

		/// Create query string:
		ArrayList pageURI = new ArrayList();
        foreach( string key in requestParams.Keys )
        {
				pageURI.Add( key  + "=" + requestParams[key]) ;
        }

		
		string url =   "http://www.google-analytics.com/__utm.gif?" + string.Join("", (string [])pageURI.ToArray(typeof(string)));
		
		/// Log url:
		Debug.Log("[Google URL]" + url);		
		
		/// Execute query:
		WWW w = new WWW(url);
		//while ( w.isDone == false ) {};
//		string d = w.data;		
		
	}

	private static long GetEpochTime()
	{
		System.DateTime dtCurTime = System.DateTime.Now;
		System.DateTime dtEpochStartTime = System.Convert.ToDateTime("1/1/1970 0:00:00 AM");
		System.TimeSpan ts = dtCurTime.Subtract(dtEpochStartTime);

		long epochtime;
		epochtime = ((((((ts.Days * 24) + ts.Hours) * 60) + ts.Minutes) * 60) + ts.Seconds);
		
		return epochtime;
	} 
	
	
}

@azeitler
thanks for the new optimizations to the script! :slight_smile:

Is this new version compatible with iPhone/iPad development in Unity?

EDIT: @azeitler, thanks for the confirmation, and thank for sharing this with the UnityCommunity! Your hard work is appreciated.

yes

Can the Google analytics js code be embedded in the unity standalone, or is it dependent on the host sites page js? I ask not as a developer, as oyu can see, but as a PM trying to prep for a game yet to be made.

any word on the compatibility of this great script with Unity3?(now that its officially released)

Hi zhx
I did an experiment in Unity3, exactly this code and doesn’t work
In log in web player luccheck6 luccheck6 luccheck6 luccheck6 … when try to acess crossdomain in www.google-analytics.com
Until now I don’t see an example that works pure in Unity3 in web player
Best

I did not have any problems actually, it upgraded without a problem as far as I know. (In a standalone though)