Using prime[31] to connect your unity game to azure mobile services

Post on 15-Jan-2015

245 views 2 download

description

Using prime[31] to connect your unity game to azure mobile services. More info at my blog: http://davevoyles.azurewebsites.net/prime31-azure-plugin-win8-wp8-unity-games-part-3/

transcript

Using prime[31] to connect your Unity game to Azure Mobile ServicesDave VoylesTech Evangelist | Microsoft@DaveVoyles

Agenda• Intro to prime[31]’s Azure plugin

• Creating a mobile service in the Azure web portal

• Installing the plugin

• How does Unity handle .DLLs?

• Compiling our project

• Walking through the code

• Azure functions

• What other options exist?

Source Code: https://github.com/DaveVoyles/prime31-azure

Intro to prime[31]’s Azure plugin

prime[31]• Free! • Runs across:

Windows 8 Store

Windows Phone 8

Does not run in the Unity Editor• Download here:

https://prime31.com/plugins#

// Prepares the connection to the Azure servers. This must be called before any other methods.

public static void connect( string applicationUrl, string applicationKey )

// Inserts a new item into the database

public static void insert<T>( T item, Action completionHandler )

// Updates an item in the database

public static void update<T>( T item, Action completionHandler )

// Deletes an item from the database

public static void delete<T>( T item, Action completionHandler )

// Queries the database

public static void where<T>( Expression<Func<T,bool>> predicate, Action<List<T>> completionHandler )

// Looks an item up to see if it is in the database

public static void lookup<T>( T item, Action<T> completionHandler )

// Authenticates a user with the service provider. Note that the service provider

// must first be setup in the Azure web dashboard! The completionHandler will

// return null in the event of a login failure.

public static void authenticateWithServiceProvider( MobileServiceAuthenticationProvider serviceProvider,

Action<MobileServiceUser> completionHandler )

prime[31]

NOTE: It’s important to note that before you can use this plugin you must download and install the Mobile Services SDK from here.

Creating an Azure Mobile Service

Creating your mobile serviceStart by heading to: https://manage.windowsazure.com/

Sign up for Azure, either through BizSpark or for a 90 day free trial

Look for Azure Mobile Services on the left-hand side of the screen

Creating your mobile service

Creating your mobile service

Creating your mobile service

Creating your mobile service

Creating your mobile service

Creating your mobile service

Creating your mobile service

Creating your mobile service

Creating your mobile service

How does Unity handle .DLLs?

What is a .DLL?A DLL is a dynamic link library. It is a collection of code and/or data, which may be used by several applications (or other libraries/modules).

So, common methods to process files, work with GUI components etc. are made available in libraries so several applications may use the same functionality.

Handling .DLLsFor example:

 Assets/Plugins/Metro 

would hold my [prime31] .DLL which connects to Azure.

Building .DLLsWhen Unity builds your project, it first grabs all of the .DLLs within the Assets/Plugins folder.

It then does another pass to see if there is a platform-specific folder containing plugins.

Is one present?If one is present, it adds those to the build.

If there are two plugins with the same name:

1. Unity prioritizes the plugin in the platform-specific folder, and

2. overwrites whatever was in the Assets/Plugins folder.

Installing the plugin

Installing the pluginDownload the plugin from the prime[31] site by registering at the site.

You’ll receive a download code immediately after, in your e-mail.

Installing the pluginImport the whole project into an empty Unity scene

Go to File –> Build Settings, located at the top-right corner of Unity. 

NOTE: Make sure that your Inspector window is visible, because we’re going to change some build settings for Windows 8 here!

Add the current scene (MetroAzureTestScene) to the build.

Preparing your build

Click on Windows Store Apps, and on the right-hand side you will see several options.

NOTE: prime[31] currently only supports C# / XMAL apps, so under Type you must select XAML C# solution.

For SDK, I’m currently building for Windows 8, and I have Unity C# projects checked.

Preparing your build

Select the button for Player Settings, and look at your Inspector window.

You should see a tab for Publishing Settings; select that. Move down to Unprocessed Plugins, and you’ll see that the size currently reads 0.

Change that to 1, and a new line appears, with the text Element 0 to the left of it.

Unprocessed Plugins

NOTE: You need to add “P31MetroAzure.dll” in this empty field, otherwise Unity never knows to build the project with your Azure plug!

Unprocessed Plugins

You’ll also need to add “Internet Client” to your capabilities section.

This allows your Win8 project to connect to the internet. It modifies the AppManifest.XML file which is generated for your WIn8 project. 

Capabilities

BuildingGo back to the Build Settings popup, and select Build. 

When it prompts you for a location, I generally create a new folder inside of my project called “Builds”, and then have more folders inside of that one for each platform. In this case, “Metro”.

Building

The finished build

Launching from Visual Studio

Inside Visual StudioSomething that threw me in a loop initially, was the fact that the project wants to deploy to an ARM device immediately.

If you hit debug “Local Machine” it will throw an error about your machine not being an ARM tablet.

Inside Visual StudioGo to Configuration Manager and change the Active Solution Platform to X86

Inside Visual StudioYou can now run your projects and deploy them via Visual Studio.

Do that, and you will be greeted with this screen:

Inside Visual StudioNOTE: On occasion, I’ll get an error when building the project.

I’m not sure of what causes this, but when I switch my deployment from whatever it is currently on (for example, Debug) to Release or Master, it suddenly builds fine.

I can then go back to Debug, and use that if I’d like.

Walking through the code

Inside Visual Studio

Leaderboard.csA container for the things you insert into your leaderboard.

It simply holds a name, score, and unique ID for each object you insert into the board.

NOTE: username and score MUST be lowercase

Endpoint and Application Key[SerializeField] private string _azureEndPoint = "<your leaderboard service>"; [SerializeField] private string _applicationKey = "<your application key>";

OnGUI()Organizes our buttons and on-screen text.

Azure functions

The Where() functionWe can update, delete, and insert things into our leaderboard, but before we can update or delete anything, we need to return some leaderboard results.

The syntax may look kind of funky, but bear with me:

The where() function// Grab all scores in our leaderboard which are <= _minScoreToReturn Azure.where<LeaderBoard>(i => i.score <= _minScoreToReturn, itemsInTheLeaderboard => { Debug.Log("queried all scores <= 100 has completed with _leadersList count:

" + " " + itemsInTheLeaderboard.Count);

_leadersList = itemsInTheLeaderboard;

// Loop through each item in the leaderboard list, and draw it to the log foreach (var item in itemsInTheLeaderboard) { GUILayout.Label("Name:" + " " + item.username + " " + "Score" + " " + item.score); } });

The Where() functionWe use a lambda function as the first parameter, which serves as an anonymous (unnamed) function. 

 i is as each object in our leaderboard list, and we are looking to pull out the scores, so the argument within this lambda function is i.score.

The Where() function

Azure.where<LeaderBoard>(i => i.score <= _minScoreToReturn,

The Where() functionThe next parameter in our Azure.Where() function is itemsInTheLeaderBoard 

You know those items we just returned from our leaderboard? Well they all get stored in this variable, which serves as list that we can now manipulate.

itemsInTheLeaderboard =>

The Where() functionI’m not quite sure if I’ve been able to return anything at this point though, so why not draw it to our log, just to be sure?

First we take the itemsInTheLeaderboard, and use the count() function (given to us by the fact that this is of type List), and verify that we have some things being returned.Debug.Log("queried all scores <= 100 has completed with

_leadersList count: " + " " + itemsInTheLeaderboard.Count);

The Where() functionNext, we need to loop through each leaderboard item in this list and draw it to the screen, because what’s the point of having a leaderboard if folks can’t see how they compare to everyone else, right?

Using a foreach loop, we iterate through each item in the leaderboard ad draw it to the screen, including the username and score.

The Where() function

// Loop through each item in the leaderboard list, and draw it to the logforeach (var item in itemsInTheLeaderboard) { GUILayout.Label("Name:" + " " + item.username + " " + "Score“ + " “ + item.score); }

The Where() functionNOTE: You MUST use lowercase values for username and score. You’ll see in our leaderboard class that I even use lowercase values.

That’s because the node.js backend we are using on our Azure leaderboard is expecting lowercase values.

Insert, Delete, & UpdateNOTE: All of the functions in this sample require you to be connected to Azure before you do anything. You must hit the “Connect Azure Service” before anything can take place!

The Insert() function

if (GUILayout.Button("Insert To Leaderboard")) {

Azure.insert(_leaderBoardItem, () => Debug.Log("inserted" + " "

+ _leaderBoardItem.username + " " + "to leaderboard")); }

Verifying through the consoleI’ve entered “Unity Tutorial Test” as the user name and “70″ as the score for the inputs.

Hit “Insert To Leaderboard” AFTER you connect, and you’ll be good to go!

Verifying in the Azure Portal

Update & DeleteTo update or Delete an item in the leaderboard, we need to perform a few steps:

1. Connect to the Azure Mobile Service2. Retrieve results from the leaderboard3. The Update & Delete buttons will now appear

on screen, beneath the newly returned results.4. Grab the latest results from the array in the

leaderboard

The Update() function// UPDATE the first (latest) thing in the leaderboard if (GUILayout.Button("Update latest Item")) {

// Grab the first item in the leaderboard list var leaderToUpdate = _leadersList[0];

// Set the item's UserName to what we entered in the UserName input field leaderToUpdate.UserName = GUILayout.TextField(_leaderBoardItem.UserName);

// Update the item in the leaderboard Azure.update(leaderToUpdate, () => Debug.Log("Updated leaderboard item:" + " " + leaderToUpdate.UserName)); }

The Delete() function // REMOVE the first (latest) thing in the leaderboard (then delete it later)

if (GUILayout.Button("DELETE LATEST ITEM"))

{

// Grab the first item in the list

var leaderToRemove = _leadersList[0];

// Removes item at the specified index

_leadersList.RemoveAt(0);

// DELETE it from the leaderboard

Azure.delete(leaderToRemove,

() => Debug.Log("Deleted latest item from leaderboard:" + " " + leaderToRemove.UserName));

}

The Update() functionSo after we've returned our results, and  the update button appears do the following:

1. Enter a new name (for example, Johnny Quest)2. Hit the "Update Latest Item" button

Now you'll see top item in the leaderboard list says Johnny Quest. Head to your Azure portal just to verify, and you'll see that it works!

The Update() function

The Update() function

What other options exist?

bitrave overview• Free! • Requires Newtonsoft.Json• Same project works on Win8 & WP8• Runs across:

UnityEditor

Windows 8 Store

Windows Phone 8

iOS

Android

Probably everything else Unity runs on

Json.NET Unity PluginNOTE: You will need the $20 Jon.NET Unity plugin to serialize the JSON data if you are running bitrave on non-Microsoft platforms. 

Microsoft platforms can use the Newtonsoft.JSON nuget package (download it from within the nuget package manager Visual studio), which is a free .DLL that is referenced from within your Visual Studio project. 

Bitrave vs. prime[31]• More platforms• Both free

Wrapping up• What are Azure Mobile Services?• Creating a mobile service in the web portal OR

Visual Studio• Compiling our project – exclude .DLLs!• Other Options – bitrave

Source Code: https://github.com/DaveVoyles/prime31-azure

That’s all!

@DaveVoyles

DavidVoyles.wordpress.com