Search Unity

Be more than mobile

Take advantage of Windows 10 momentum and new market opportunities in the Windows Store.

Porting guides

Introduction

Building games with Unity has become increasingly popular, especially for leveraging a single codebase to access multiple platforms and device types. The same is true for building games for Windows 10 with the Universal Windows Platform (UWP). In this whitepaper, you’ll learn how to use what you already know about Unity to build games for UWP. We will cover topics such as:

  • compiling your game for UWP
  • understanding Windows environment best practices
  • implementing platform-specific features
  • understanding key plug-ins
  • publishing to the Windows Store

To illustrate the details of bringing a Unity game to UWP, we will use an actual game to help walk through the various aspects and considerations involved in exporting a Unity game to UWP and then deploying it to the Windows Store.

Note: This guide assumes you are already familiar with the basics of using Unity3D. You can learn more about using Unity3D at any time by checking out the Unity tutorials.

Requirements to write a UWP game with Unity

To develop, compile, and submit a Unity game to the Windows Store, you will need:

  • Unity 5.3.5. Either the Unity free version or Unity Pro will work. The add-ons for publishing to the Windows Store are free for both basic and Unity Pro users.
  • Visual Studio. You can use any Visual Studio SKU, including the free Visual Studio Express. To target Universal Windows Platform, you will need Visual Studio 2015 Update 1.
  • Windows 10. If you do not own a Windows 10 license, you can get a 90-day evaluation version. If you are running Mac OS X or will install on Apple hardware, check different options for installing using Boot Camp, VMWare, or Parallels.
  • Microsoft account. You will need a free Microsoft account to get a developer license.
  • Windows Store developer account. This will be needed to submit your game to the Windows Store. During this process you will register and get verified as an individual or as a business who can submit apps and games to the store. This registration is shared with Windows Phone (one registration can submit apps to both stores). There may be a small registration fee for individuals to sign up, although free Dev Center accounts are often available through Microsoft-sponsored programs (e.g. for students or startups).
  • Windows 10 test devices. While the simulator can simulate multi-touch and different display resolutions, we recommend you test on a real ARM mobile device with touch capability if you are developing a mobile/touch experience.

This document was created with Unity 5.3.5, Visual Studio 2015 Update 2, and Windows 10 Version 1511. For your benefit, it is recommended that you use, at a minimum, Unity 5.3.2 and Visual Studio Update 1 as older versions may have a different application programming interface and other possible incompatibilities.

Windows Store

Windows Store now has a single place to submit and upload your UWP apps. You can still target devices using older operating systems, but for this document, we will be focusing on submitting your game as a UWP app to Windows Store.

Nuget

NuGet is the package manager for the Microsoft development platform including .NET. It allows developers to find third-party libraries and add them to projects as dependencies. You can use NuGet to provide any Windows libraries that you need to use natively. NuGet can also be used to manage DLLs that are called from your scripts in Unity.

NuGet is also necessary for porting Unity games to UWP. When you export a project from Unity to a Visual Studio UWP app, Unity depends on NuGet to install all the libraries needed to target .NET Core.

Setting up Unity to deploy to Windows Store

In this section, we are going to cover what is required to take an existing Unity game and get it ready for deploying to Windows Store as a Universal Windows Platform (UWP) game. We will cover the following:

  • Enable developer mode in Windows 10
  • Enter game details in Unity
  • Export to UWP in Windows 10
  • Build Solution in Visual Studio 2015 Update 2 with Window 10 SDK
  • Associate your game with Windows Store
  • Add required images/content (e.g. logo, icon, splash) if not already done in Unity
  • Run Windows App Certification Kit (WACK)
  • Publish to Windows Store

Enable developer mode in Windows 10

A developer license is no longer required for each device that you want to use to develop, install, or test your app. Instead, you may now enable a device just once for these tasks from the setting for the device.

Enable your Windows 10 devices

For Windows 10, whether using a desktop, tablet, or phone, you need to enable that device for development under System Settings.

To do so, navigate to System Settings and choose “Update & security.” Then choose, “For developers.” From here, you can simply select and enable “Developer mode.”

You can find more details on how to do this here.

Enter game details in Unity

One of the first steps in preparing your game for Unity is to make sure you have the right build settings configured for it.

In order to build Unity games for Universal Windows Platform (UWP) apps, you will need the following:

To configure your settings in Unity, first click “File,” then “Build Settings.”

Next, click the Player Settings… button.

On the Player Settings window, you can then enter your game details.

If you choose to, you can also add logo and tile images in the Player Settings window that will be displayed in Windows Store. As with many things in building Unity apps for the Windows Store, however, there are multiple ways to accomplish this; you can also defer adding images through the Unity IDE and do it later through Visual Studio instead.

Your build settings are now properly configured in Unity3D to allow you to export to UWP.

Export to Universal Windows Platform

This section will review the existing Unity support for Universal Windows Platform (UWP) apps and how to export from Unity to UWP.

Unity3D has had support for UWP apps since Unity 5.2. Currently, you can export to UWP by selecting the Universal 10 SDK from the Windows Store platform in the Build Settings window, as illustrated below:

Unity 5.3.5 will export Visual Studio 2015 solutions files, which can then build and run on Windows 10 devices.

Three architectures are supported: ARM, x86, and x64. In addition, you can use .NET Core 5.0 in your game projects.

Clicking on the Build button in the Build Settings window will prompt you with a Build Windows Store dialog to select a folder for building your game.

Once you have selected the folder, Unity will begin building your game, targeting the platform you selected. This can take several minutes if you have a large game:

A Windows Explorer window should now display the folder containing all the files generated by Unity.

For more details on this process, consult Unity3D’s documentation on Windows.

Build Solution in Visual Studio 2015 Update 2 with Windows 10 SDK

In order to sell or distribute your Universal Windows Platform (UWP) app, you need to create an appxupload package for it. This package facilitates selling your app on Windows Store or distributing it to other users. When you create the appxupload, another appx package will be generated to use for testing and sideloading. You can distribute your app directly by sideloading the appx package to a device.

For Windows 10, you generate one package (.appxupload) that can be uploaded to the Windows Store. Your app is then available to be installed and run on any Windows 10 device.

Note: If you need to create an app package for a Windows 8.1 app, follow these instructions.

You are now ready to compile your game in Visual Studio.

First, select either x86 or x64 as the platform.

From the menu, click Build -> Build Solution.

Allow the NuGet Package Manager to restore packages.

Click Run and ensure you have selected Local Machine.

Verify the build succeeded.

Once you’ve done this, you are ready to sell your app in Windows Store. If you have a line-of-business (LOB) app that you don’t plan to sell because it is for internal users only, you can side-load this app to install it on any Windows 10 device.

For more details, see Packaging Universal Windows apps for Windows 10

Associate your app with Windows Store

From the Projectmenu, choose Store -> Associate App with the Store....

When you do this, most of the fields in the Packaging tab of the manifest designer will be automatically updated. The following values are downloaded to the app manifest file for the current project on your local machine:

  • Package Display Name
  • Package Name
  • Publisher ID
  • Publisher Display Name
  • Version

If you override the default package.appxmanifest file by creating a custom .xml file for the manifest, you can’t associate your app with the Store. If you try to associate a custom manifest file with the store, you will see an error message. Creating a custom package manifest is discouraged.

For more details, see Packaging Universal Windows apps for Windows 10.

Getting ready to submit your app to the Store

Once you have created your app by reserving a name, you can start working on getting it published. The first step is to create a submission.

You typically start your submission when your app is complete and ready to publish. However, you can start entering info even before you have written a single line of code. The submission will be saved in your dashboard so you can work on it whenever you are ready.

After your app is published, you can publish an updated version by creating another submission in your dashboard. Creating a new submission lets you make and publish whatever changes are needed, whether you are uploading new packages or just changing details, such as price or category.

To create a new submission for an app, click Update next to the most recent submission shown on the App overview page.

App submission checklist

Unity provides you with the minimum assets required for submitting an app, but it is recommended that you provide your own images and assets. The following is a screenshot of the Visual Assets section of the Package.appxmanifest file:

You can review all of the assets provide by the build process.

For more details, see App submissions on MSDN.

Run Windows App Certification Kit (WACK)

To give your app the best chance of being published on Windows Store, or becoming Windows Certified, validate and test it locally before you submit it for certification. This topic shows you how to install and run the Windows App Certification Kit. WACK will run a series of tests against your app for things such as performance and API compliance. For more details on specific tests carried out by this kit, refer to the following topics:

Prerequisites

If you are developing a Universal Windows Platform (UWP) app, you must…

To install Windows App Certification Kit version 10, which is included in the Windows Software Development Kit (SDK) for Windows 10, you must first create an app package to run the test. From the Project menu, choose Store -> Create App Packages…:

Once the package creation completes, you will be presented with the following window where you can launch the Windows App Certification Kit (WACK):

When you launch WACK, you will be presented with the following dialog:

Click Next to proceed with the validation steps. Do not be alarmed if you see multiple windows pop up. The tool is simply running your game and performing tests. These tests can take several minutes to complete.

Once the tests have completed, you will be presented with the following window. If the tests failed, you will be able to review them to make corrections and then repeat this process to pass the tests.

Clicking the “Click here to view the results” link will open up a browser with the test results.

Here you can review every test and find out what exactly failed and correct the issue. After you have corrected all the issues and rerun the tests, you should get the following results:

For more details, see Using the Windows App Certification Kit on MSDN.

Publish to Windows Store

Now that your game is built and uploaded, you need to go into your developer account in order to submit it to the store. Follow the following steps in order to begin the submission process.

  1. Open a browser and go to https://dev.windows.com.
  2. Login to your account and click on the Dashboard link.
  3. Select the name of the app package you created in Visual Studio.
  4. Click on "Start your submission."
  5. In this next step, you will need to fill out information about your game before you are allowed to complete your submission. Clicking on any of these links will open up a new page that will walk you through the details of the submission process.

The Packages page is where you upload all of the package files (.xap, .appx, .appxupload, and/or .appxbundle) for the app that you are submitting. You can upload packages for any operating system that your app targets in this step.

When a customer downloads your app, Windows Store will look through all of your app’s available packages and will automatically provide each customer with the package that works best for that customer’s device.

For details about what a package includes and how it must be structured, see App package requirements. You may also want to learn about…

Uploading packages to your submission

To upload packages, drag them into the upload field or click to browse your files. The Packages page will let you upload .xap, .appx, .appxupload, and/or .appxbundle files.

Note: For Windows 10, you should always upload the .appxupload file here, not the .appx or .appxbundle. For more info about packaging Universal Windows Platform (UWP) apps for the Store, see Packaging Universal Windows apps for Windows 10.

If issues are detected with your packages while validating them, you will need to remove the package, fix the issues and then try uploading it again. For more info, see Resolve package upload errors.

Reference Implementation

In this section, we will be referencing a simple 3D Basketball game written by Jb Evain onstage at Build in less than 20 minutes. If you would like to create the game from scratch, you can follow along with Jb’s talk. The only external asset you will need to create the game is this Hoop.3ds file.

If you would rather just download the finished project package, Basketball-At-Build.zip, it is complete and playable. You will be able to follow along with the rest of this section once you’ve extracted the compressed file.

The following is a scene from the completed game:

Basketball

In the next few steps, we will use a game to demonstrate the steps outlined above for getting a game ready for submission to Windows Store.

If you are building the game from scratch, you will need to follow these steps. If you have downloaded the completed project, you can skip steps 1 through 8.

  1. Open up Unity and create a new Project You can call it “Basketball” or “Awesome Game” if you like.
  2. Create a Game scene.
  3. Drag Hoop.3ds from its download location into the Assets pane.
  4. Select Assets -> Import Packages -> Characters.
  5. Once the asset has been downloaded, click on the Import button. This will bring all the assets into your project.
  6. Create a sphere and apply materials to it so it has color and bounces.
  7. Position components in the scene.
  8. Write the Shooter script so you can throw balls at the basketball hoop.
  9. In the Project tab, expand the Assets tree and click on the Scenes folder.
  10. Double-click the Game scene to load it. Before we go any further, let's run the game and see how it works.
  11. Now that we know that the game runs, we can test your skills!

Creating our Visual Studio project with Unity

Now that you have imported and tested the game in Unity, let’s move on to creating a Visual Studio solution.

In the menu, click on File | Build Settings… to open up the Build Settings window and make sure that you have a scene selected under the Scenes In Build view. You will want to ensure that…

  • Platform is set to Windows Store (if it is not, click Windows Store -> Switch Platform).
  • SDK is set to Universal 10.
  • UWP Build Type is set to XAML.
  • Unity C# Projects and Development Build are both checked.

Next, click on the Player Settings… button and make sure that the information there is correct. This game is designed for Landscape mode. Verify that the Default Orientation has Landscape selected:

Finally, click on the Build button from the Build Settings window. You will be prompted to select a folder where you wish to build the project. This is where your Visual Studio solution and project will be created.

Using Visual Studio to create an App Package and WACK

We have successfully created our Visual Studio solution and should now be able to transition over to it and continue with setup there.

Double-click on the solution created for you.

Visual Studio 2015 will open loading three projects. Do not be concerned if you see errors. Visual Studio loads resources asynchronously. Simply wait for all resources to be loaded and build the project in Debug mode by select Build | Build Solution from the menu.

Next, you will want to…

  1. Verify that the build was successful.
  2. Switch the mode from Debug to Master. This is important as you will need to submit your UWP apps to the Windows Store using the Master mode. (Master mode removes safety checks and disables the profiler in order to provide the best performance.)
  3. Select Store | Create App Packages... from the Project menu.

If this is your first time or several days have passed, you will be prompted to authenticate with your Windows Store developer credentials. You will need to enter a security code to verify your credentials.

If your build succeeds, continue by clicking on the Launch Windows App Certification Kit button. This testing process make take quite some time to validate that your game is ready to be submitted to Windows Store.

If everything passes, you should see the following screen:

Designing your Unity game for UWP

Unity provides a mature toolset that allows you to target many platforms. This includes tooling support for Universal Windows Platform (UWP) apps. Unity tooling can handle the following areas, among many others:

  • Multiple resolutions and screen resizing
  • Aspect ratios

Multiple resolutions and screen resizing

Out of the box, your Unity game is able to handle multiple resolutions and screen resizing. One aspect of this support that may not be intuitive but is still critical to your game is your menu and heads up display (HUD).

Unity provides a new user interface system, Unity UI. This new UI system removes the need to use third-party plugins and facilitates mature interfaces within your game. It is important to configure your menu and HUD correctly and test on different resolutions. If you remember your days in Windows Forms or WPF, you will recall that you could anchor your UI elements so that your elements would resize along with the screen. Unity provides this same capability. In addition to anchor positions, you can define whether your UI elements will resize or remain the same when the screen resizes.

Aspect ratios

Just like with multiple screen resolutions and screen resizing, Unity supports multiple aspect ratios. It is always important to test the various aspect ratios you wish to support within your game, but Unity makes is very easy to test against any aspect ratio you like.

You will want to test on emulators as well as target devices you have access to in order to ensure that you have everything ready.

Visual Studio 2015 Tools for Unity

Visual Studio comes loaded with tools to help with getting your Unity game ready for publishing to the Windows Store. Among them are the following:

  • Unity Project Explorer
  • Writing scripts and debugging in Visual Studio
  • Graphics Debugger

Visual Studio Tools for Unity

Starting with Unity 5.2, you no longer need to import Visual Studio Tools for Unity separately. In Visual Studio 2015, simply go into Tools | Extensions and Updates to install Visual Studio 2015 Tools for Unity.

This following section will walk you through the steps required if you wanted to get the latest version of VSTU or are using a version of Unity prior to 5.2. If you are using Visual Studio 2015 with Unity 5.2 or above, the following steps are not necessary and may safely be skipped.

Visual Studio Tools for Unity allows you to write and debug your Unity games inside Microsoft Visual Studio. In addition to the ability to add breakpoints and evaluate variables and complex expressions, you can also browse your project as if you were in Unity with the Unity Project Explorer. Finally, you will see the exact same console output inside Visual Studio that you would get in Unity.

The following is a screenshot of installing Visual Studio 2015 Tools for Unity. Make sure you accept the terms by selecting the checkbox:

Once it completes, you will get a dialog indicating completion of the installation:

Now that we have completed the installation, we need to open Unity and add this tool to our project.

You will be presented with the following Unity dialog. Leave everything selected and click on the Import button:

You will see that a new folder was created in your Project hierarchy:

You will want to be sure that you have your Build Settings configured for using Visual Studio properly as indicated below. Make sure you have “Unity C# Projects” and “Development Build” checked:

You are now ready to write scripts and debug using Visual Studio. Remember: the installation process was only necessary for versions of Unity that were older than 5.2.

Writing scripts and debugging in Visual Studio

If you double-click on a script in Unity, it will launch Visual Studio. For example, if we selected the Shooter.cs script and launched it in Visual Studio, we would see the following

Now, if we wanted to debug the GetButtonDown call, which initiates throwing balls, we could add a breakpoint on line 12 and then click the Attach to Unity button:

Now, back in Unity, all you need to do is click the Play button and the game will start. Since we know that Update will be fired, we will see the game pause on line 12 in Visual Studio if we click on the left mouse button:

Your workflow with debugging is the same as with any Visual Studio project.

Graphics Debugger

Visual Studio 2015 comes with a very powerful graphics debugger that will allow you to optimize your game.

First, let’s make sure that you have the Graphics Tools added to your system. In Windows, go to Settings, select System, select Apps & Features, select Manage optional features. If it is installed, you should see Graphic Tools:

If you don’t have this, select Add a feature and, in the list, click Graphic Tools. Please refer to the MSDN documentation on Graphics diagnostic tools if you are having trouble installing it.

You will need to use the Visual Studio build from Unity and open up the game using Visual Studio in order to use the Graphics Tools. Inside Visual Studio, you can use this tool from the menu by clicking Debug | Graphics | Start Graphics Debugging, as shown below:

Once the game launches, you will be presented with the following UI:

Click on the Capture Frame icon to capture the current frame of the game. You can capture different parts of your game play.

Double-clicking on a Frame will present you with detail analytics concerning that frame. You are able to move forward and backwards on the draw calls in the Graphics Event List pane, as well as select individual pixels and view the Graphics Pixel History pane:

Take note that the graphics diagnostic file can become very large. If you would like more information, you may visit Visual Studio Graphics Diagnostics.

Windows Store Asset Generation

In order to get your app submitted to the Windows Store, you will need to provide images in the correct size. There is a Visual Studio Extension that will come in handy for just this occasion: the UWP Tile Generator. You will be able to select an image and it will create all the sizes you need in a zip file.

Understanding differences between Unity and UWP apps

Unity uses a framework called Scripting backend to support scripting. It currently supports three backends: Mono, .NET and IL2CPP. When your app targets Windows Store, only .NET and IL2CPP are available. You can select the Scripting Backend by clicking on the Player Settings button from the Build Settings window in Unity.

In the Unity IDE, scripts using .NET are referencing .NET version 3.5. When your game is exported to Visual Studio, however, all your C# code is compiled against .NET Core, which is a subset of .NET version 4.5. ( Note: If you use IL2CPP as the scripting backend, however, your Windows Store app will continue to use .NET 3.5.) To illustrate this, try writing the following line of code into a Unity script:

        
          System.Collections.SortedList lst = new SortedList();
        
      

When youF12 on the SortedList in Visual Studio in order to view the type definition, you'll notice that this class is found in the library mscorlib.

If you insert the same code into your exported project and F12 on the SortedList type, you will find that this version of the class is contained in a NuGet package that is part of .NET Core.

In the past, this could lead to issues when there were types or methods in .NET 3.5 that were not in .NET Core. This, in turn, required helper libraries like WinRTLegacy to fill in the gaps and provide not only types but also extension methods.

Tip: Be cautious around guides to missing types between Unity and .NET Core. Many of these are outdated and not necessarily accurate.

While it is still important to understand this essential difference between Unity and UWP, problems with missing types and methods when porting from .NET 3.5 to .NET Core continue to improve as .NET Core grows. For instance, System.Threading.Tasks, which were introduced after .NET 3.5, are a part of .NET Core. You may also encounter problems going the other way as you attempt to implement features from .NET Core that are absent in .NET 3.5.

It is worth noting that if you use IL2CPP as your scripting backend, the API surface between the Unity editor and your Windows Store app will become identical.

Platform specific features

Because Unity and the Universal Windows Platform (UWP) are different platforms, porting between them involves advantages as well as challenges.

Performance Optimization

UWP apps use .NET Native, which generates optimized, native machine code. This leads to faster launch times and lower battery consumption for your games. The impact of these optimizations will vary based on the complexity of your game, but Unity games that use the .NET scripting backend tend to get a boost from them. In a generated game project, only a “Master” build configuration will compile to .NET Native.

Directives

If you wanted to invoke a UWP Toast or a Tile from your game, how would you do this? These features are not a part of .NET 3.5, the Scripting backend used when you develop in Unity. In this case, it would seem like your code would work fine once you exported it to Visual Studio but would never work in the Unity IDE.

In order to work around issues like this, Unity provides a library UnityEngine.WSA, which contains stub classes such as Application, Cursor, Launcher, Tile and Toast. You can program against these types in your Unity C# scripts in order to interop between Unity and UWP.

A second technique for managing features that are missing in .NET 3.5 is to use NETFX_CORE directive in your scripts. This directive is used to ignore code blocks that you know will not compile in .NET 3.5 but which you need in your game when it is compiled against .NET Core. The following example, which can be found on the Unity bitbucket repository, demonstrates how code that would fail in the Unity IDE can be ignored by using directives.

        
          #if NETFX_CORE
          async
          #endif
          void UpdateTile(byte[] png150x150)
          {
          #if NETFX_CORE
              // In order to change tile image, we should change the uri too
              // in this example we store images in applications local storage
              // we must also take care of cleaning it up
              StorageFolder localFolder = ApplicationData.Current.LocalFolder;
              StorageFolder tilesFolder = null;
              try
              {
                  tilesFolder = await localFolder.GetFolderAsync("tiles");
              }
              catch (Exception)
              { }
              if (tilesFolder != null)
                  await tilesFolder.DeleteAsync();
              tilesFolder = await localFolder.CreateFolderAsync("tiles");
              string tileFile = "tile" + counter++ + ".png";
              StorageFile file = await tilesFolder.CreateFileAsync(tileFile, CreationCollisionOption.ReplaceExisting);
              await FileIO.WriteBytesAsync(file, png150x150);

              string txt = textToTile ? text : "";
              Tile.main.Update("ms-appdata:///local/tiles/" + tileFile, "", "", txt);
          #endif
          }
        
      

Occassionally you will want to be more specific and use the Unity_WSA_10_0 directive instead of relying on NETFX_CORE. While the latter is a directive for any Windows Store app, Unity_WSA_10_0 is used for Windows 10 devices in particular.

Writing Plugins

Plugins can also be affected by the differences between .NET 3.5 and .NET Core. Sometimes the code is compatible and you will have no difficulties. When it is not, however, Unity allows you to configure your app in such a way that two different versions of the same plugin are used, one for the Unity IDE (which is based on .NET 3.5 APIs) and the other for the full game (which is compiled against .NET Core).

In order to implement multiple plugins, you must follow certain rules. Your plugins are required to share the same name and have the same assembly version number. The two plugins must also be placed in separate folders. For example, your Editor compatible plugin should go in ..\Assets\Plugins\MyPlugin.dll, while the UWP-specific plugin goes in ..\Assets\Plugins\WSA\MyPlugin.winmd.

You also need to configure the version of your plugin written for the Editor as the placeholder for your .NET Core plugin – letting Unity know which library is the stub and which one is the live version that will be deployed to the Windows Store.

Select Assets\Plugins\MyPlugin.dll in your Unity Project Explorer and check Editor as the platform.

Then go to Assets\Plugins\WSA\MyPlugin.winmd and select Windows Store Apps as the correct platform for that plugin.

To help clarify this process, we are going to walk through building a set of plugins.

Open Visual Studio 2015 and create a new project called “MyPlugin”. Use the project template for a Visual C# | Windows | Universal | Windows Runtime Component. (You could also use a Class Library project template, instead, but the Windows Runtime Component has some interesting features, such as being consumable from any windows runtime language projection, which provide an extra benefit.)

Right-click on your solution and select Add -> New Project. This will be the stub version of the library that is only used in the Unity editor. Since it will compile against .NET 3.5, it needs to be created using the Visual C# | Windows | Classic Desktop | Class Library project template. Call this project “MyPluginStub,” as the same name cannot be used for two projects in the same solution.

Because the two libraries have to have the same name, you need to configure the output file for MyPluginStub to be called MyPlugin, just like your other project. To do this, right-click on the MyPluginStub project in Solution Explorer and select Properties. In the Application tab, change both the Assembly Name field and the Default namespace field to “MyPlugin” in order to match the other project. While you are doing this, you should also change the Target framework field to “.NET Framework 3.5.”

Delete the Class1.cs files that Visual Studio created for each of your projects. Then, create a new class in the MyPlugin Windows Runtime Component project called “Foo.cs.” Instead of creating a similar class for the Windows Desktop project, we’re going to share Foo.cs by adding it as a Linked file.

You can now edit the same physical file, Foo.cs, from the MyPlugin project as well as the MyPluginStub project. Examine the file in the code editor from both projects. You’ll notice that when you look at it from MyPluginStub, Visual Studio will place red squiggles around your using statement for System.Threading.Tasks This is because the type exists in .NET Core but does not exist in .NET Framework 3.5.

We could simply delete that line to fix the error since we aren’t planning on using it. Instead, however, we’re going to test for a directive to demonstrate how it works. Replace the using statement for Tasks with the following three lines of code.

        
          #if NETFX_CORE
            using System.Threading.Tasks;
          #endif
        
      

After adding this, you should find that the projects will compile once again. We still need a method for the Foo class. Naturally, it will be called bar. Bar should return one message if it is being called from the Unity editor and a different one if it is being called inside the Windows Runtime Component. Add the following implementation of the bar method to your Foo class. (As you do this, also add the “sealed” keyword to your class declaration as Runtime Components require this.)

        
          public sealed class Foo
            {
              public string Bar()
              {
                #if NETFX_CORE
                  return "Windows Store version of the plugin.";
                #endif
                  return "Unity Editor version of the plugin.";
              }
            }
        
      

Build the two libraries.

Next, you will configure your Unity project to use these libraries. Open your project in Unity and create a new folder under Assets called Plugins. Beneath Plugins, create another directory called WSA (abbreviated for Windows Store Application). Find the MyPlugins.dll file from your MyPluginsStub project and drag it into ..\Assets\Plugins. Then find the MyPlugins.winmd file you compiled and drag that into ..\Assets\Plugins\WSA.

Click on Plugins\MyPlugin in the assets pane. This will cause the MyPlugin Import Settings to display in the Inspector pane. Deselect “Any Platform” and select Editor instead. This will tell the IDE that this is the version of the library that should run when you are in the Unity Editor.

Next, go one level down and select Plugins\WSA\MyPlugin. The inspector should have WSAPlayer already selected for you and no other platforms. This tells Unity that this is the version of the library you want to published to the Windows Store. Go down to the Placeholder field and find your stub library at the root of the Plugins folder. By doing this, you explain the relationship between the two libraries. Plugins\MyPlugin.dll is the placeholder for your actual library, Plugins\WSA\MyPlugin.winmd.

It’s time to test the two libraries to make sure they are properly configured in Unity. Create a new C# Script in Unity called “TestFooBar.” Create a private instance of the Foo class and write out the return value of Bar in the Logger.

        
          using UnityEngine;
          using System.Collections;
          using MyPlugin;

          public class TestFooBar : MonoBehaviour {

            private Foo testFoo = new Foo();
             // Use this for initialization
               void Start () {
                  Debug.Log(testFoo.Bar());
                }

            // Update is called once per frame
              void Update () {

              }
            }
        
      

Finally, drag this script onto one of your game objects, like Player, in order to attach it. This ensures that the script’s Start method will be called. Run the game in Unity and, if all goes according to plan, the correct message should appear in the Console pane.

Finally, go to Build Settings and click on the Build button to export your project to Visual Studio.

Run your game through Visual Studio this time and you should see the following message in your Visual Studio Output Window:

This plugin example is the foundation for almost all interactions between the Universal Windows Platform (UWP) and Unity. If you are able to successfully get the right messages to appear in your consoles, then you know most of what you need to know to encapsulate UWP code and access it from your Unity game.

Advertising

You can run Microsoft Ads as a Unity plugin by downloading and installing Unity Plugins for Windows Store and Azure Services. The plugin also contains APIs for in-app purchases, license checks, and receipt validation.

The easiest way to use the Unity plugins for Windows Store is to download the Unity package from GitHub and import it into your app using the Assets | Import Package | Custom Packages in Unity Editor. Once the package is imported, you’ll have the proper binaries located in the Unity Plugins folder and the Unity Plugins\WSA folder.

Alternatively, you can use the latest Microsoft Store Engagement and Monetization SDK extension from your exported UWP app to display banner ads and video interstitial ads. The Microsoft Store Engagement and Monetization SDK integrates the advertising features of the Microsoft Universal Ad Client SDK with other features related to Store services in a single unified installer.

Analytics

Collecting analytics about your players can be done either through the Unity platform or through the Universal Windows Platform (UWP). You can also choose to use both platforms together to collect complementary data. If you want to go the Unity route, you will need to link your project to a Unity Services ID and then enable analytics for your project. More information can be found in the Unity Manual.

Once you have deployed your game, data will automatically be collected for you on your Windows Dev Center Dashboard. The dashboard will keep you updated with reports on:

  • Acquisitions
  • Health
  • Ratings
  • Reviews
  • Feedback
  • Usage
  • IAP acquisition
  • Ad mediation
  • Advertising performance
  • App install ads
  • Channels and conversions

If it is enabled, you will even be able to view usage telemetry for your game.

Finally, you can also use REST APIs to view these analytics in a way that is most useful for you without needing to go through the Windows Dev Center.

In-App Purchases (IAP)

Because Unity games exported to the Universal Windows Platform (UWP) rely on two platforms, Unity as well as UWP, you have two options for enabling In-App Purchases. You can use Unity IAP or the Unity Plugins for Windows Store and Azure Services.

To use Unity IAP, you need to set up a Unity Services Project ID through the Services window in Unity. This will lead you through a series of dialogs to enable your IAPs for Windows Store. More details are available on the Unity website. Be aware that Unity IAP will not work with the IL2CPP scripting backend.

With the Unity Plugins for Windows Store, you use the Store API to retrieve your listings from inside a Unity script file. You first need to create In-App Products for your app through the Windows Store Dev Center. Then you can update your app to list and allow purchases of your IAPs. The essential call, made through the plugin, requires you to invoke the LoadListingInformation method to retrieve your In-App Products, as shown in the sample code below.

        
          Store.LoadListingInformation((response) =>
          {
            if (response.Status == CallbackStatus.Failure)
              {
                prettyPrintErrors("LoadListingInformation", response);
                return;
              }

            prettyPrintSuccess("LoadListingInformation", response);
            text.text = "\nFinished Loading Listing Information" + text.text + "\n";
            Debug.Log(response.Result.Description.ToString());
            foreach (var productListingKey in response.Result.ProductListings.Keys)
              {
                Debug.Log("Key: " + productListingKey + " value: " + response.Result.ProductListings[productListingKey].Name);
              }
          });
        
      

The full example implementation demonstrating how to use the Store API can be found on GitHub.

Best Practices

As you complete the core of your game, there is some polishing you will want to perform to make your app ready for Windows 10 family of devices. In this section, we will cover several best practices to ease your deployment to the Windows Store.

Splash screen and loading progress

When your game launches, it’s important to show a progress indicator so the user knows that the game is not frozen or stalled.

In this write up, we will assume you are using a XAML project. If you are not, most of the concepts here will still apply to a DirectX project but the implementations will be quite different.

There are two key stages to the loading of a game on Windows Store using Unity

  1. App Splash Screen
  2. Extended Splash Experience

The initial splash screen image will be shown by the OS and you can configure it by updating your applications manifest as follows:

Windows will show the initial app splash screen only during the time it takes the OS to load the Page (written in XAML markup) that will host your Unity scenes.

Usually, the unity scene will take longer to load. To create an extended splash experience, you will want to use XAML to show the same splash image again with a progress indicator on top to the user while your Unity scene loads. In MainPage.xaml, you will add a progress bar alongside the splash screen image.

        
          <SwapChainPanel x:Name="DXSwapChainPanel">
            <Grid x:Name="ExtendedSplashGrid" Background="#222C37">
              <Image x:Name="ExtendedSplashImage" Source="Assets/SplashScreen.png" 
                VerticalAlignment="Center" HorizontalAlignment="Center"/>
              <ProgressBar x:Name="SplashProgress" Foreground="#FFFFFFFF" 
                Background="#FF333333" Maximum="10000" Width="320" Height="25"/>
            </Grid>
          </SwapChainPanel>
        
      

In MainPage.xaml.cs—the code-behind file for the XAML UI—use the constructor to start a timer which will make the progress bar tick along providing some visual feedback to the user.

Device form factor

One code base across many form factors is a key feature of the Universal Windows Platform (UWP), but games may still require some tailoring and optimizations for specific form-factors. Most often, these include input mechanisms (e.g. touch, keyboard, mouse, gamepad), windows resizing, optimization of resources and assets, and implementation of native platform integration with each specific form-factor.

Orientation support

Due the predominantly widescreen aspect ratio on new devices, the Unity editor will export projects that default to landscape orientation. If your game supports portrait orientation, you will need to change the app manifest in Visual Studio. You cannot do this in the Unity editor.

To change the manifest, double-click in the Package.appxmanifest file, which you can find on the root of your Windows Store Visual Studio project. In the manifest editor, check the orientations you want to support.

The orientation APIs (Input.deviceOrientation and Screen.orientation) work well within Unity. You can use these to query the device’s orientation and even set the orientation for specific scenes.

Windowing support

Universal Windows Platform (UWP) apps are hosted in resizable windows instead of running full screen as they did in Windows 8 and 8.1, so windowing is now a consideration for your games and applications.

Most of these differences are transparent to you as a Unity developer because the Screen.height and Screen.width properties still report the available space in native (pixel) sizes.

When the user changes the size of the window, the recommended practice is to pause the game so that the user can decide what to do next. Since windows can also lose focus in Desktop mode, where multiple windows can be open at the same time, you should also handle focus changes and pause when your game window loses focus.

Pausing and resuming your game

In Windows, the Unity game engine typically takes care of pausing and unpausing automatically when your game loses focus. In scenarios where you might want to pause the game outside of automatic application suspension, such as during navigation between XAML pages, you can call the UnityPause method.

If you need to do something extra when application is about to pause, OnApplicationPause callback in your scripts instead.

Gamepad and mouse input

The Windows family of devices supports a wide range of inputs, from keyboard and mouse to touch to gamepads. Fortunately, all of these modes of input are not only well supported by Unity but also well abstracted through Unity’s Input Manager.

In the shooter behavior for our Basketball game, we wait for the “Fire1” Input Axes to be fired before having the game throw a ball.

        
          void Update()
            {
              if (Input.GetButtonDown("Fire1"))
              {
                var instance = (Rigidbody)Instantiate(this.prefab, transform.position 
                        + (transform.forward * 1.05f), transform.rotation);
                instance.velocity = (transform.forward + transform.up / 2) * this.speed;
              }
            }
        
      

“Fire1” is actually mapped, by default, to both the left mouse button as well as a gamepad/joystick button as shown below in the Input Manager. To view the Input Manager in the Unity IDE, select Edit -> Project Settings -> Input.

On an Xbox One controller, “joystick button 0,” which is mapped to “Fire1,” happens to be the A button. There are also inputs already mapped to the FPSController component for movement and jumping. Mouse movements, left, right, up and down keyboard keys, as well as a, d, s, w keys, and the left joystick on the Xbox One controller all move the player by default. The right mouse button, space bar, and Xbox B button all make the player jump.

You can also further customize your inputs for custom experiences by remapping inputs to axes or even adding more axes to support your game. You can learn more about virtual axes in the Unity Manual.

Conclusion

This document has shown you how to configure and export your game from Unity to a Universal Windows Platform (UWP) project in Visual Studio. It has also covered how to submit your UWP game into the Windows Store. We have covered some of the subtle differences between the Unity platform and the Universal Windows Platform. We have also covered platform specific code and features that you should be aware of as a game developer. Finally, this document has covered best practices for polishing your game for publication.

References

Back to Top
Got it

We use cookies to ensure that we give you the best experience on our website. Click here for more information.