Jumpstart to Windows Phone and Unity 3D

TwitterFacebookRedditGoogle+EmailPinterest

EDIT: This is now also syndicated on the Nokia Developer Wiki here.

I’m currently sitting on a 12 hour flight from Amsterdam to Johannesburg, South Africa. So writing this is a far more compelling option than watching bad quality movies on a grainy 7” screen.

The beta of Unity 3D came out yesterday (a couple days ago by the time I will be able to post this) for Windows Phone 8, and it’s awesome. My biggest problem with it at this stage is that because of how easy it is, it feels very close to cheating – but hey, time is money and why should you be wasting time fighting with technical problems when you could be using it to make your idea a reality?

For those living under a medium-sized boulder, Unity 3D is middleware to create cross-platform games quickly and easily – and it excels at that. It is made up of the main IDE (which has free and paid versions) and then an exporter for each platform (desktop is free, but all the mobile platforms require a normal or pro purchase).

Exporting to Windows Phone is a bit different to how it traditionally worked on the other platforms. Instead of spitting out a XAP file ready to be uploaded to the store, it creates a normal Windows Phone solution that resembles the Direct3D and XAML template. This means you can add Windows Phone specific code on top of your Unity 3D game – which both breaks the cross-platform goal and is awesome at the same time (for example, our current game at RogueCode would be impossible without this).

Below I will first show you the basics of Unity 3D by creating a simple scene where a ball bounces around, then I will show how to fire events in a Unity3D C# script, and react to that in your Windows Phone project code.

I did the spouse-test on this tutorial, and my wife (who is not in IT) managed to follow the whole thing fine (her smoke turned out purple of course). So you have no excuse Smile with tongue out

Before getting started, here is a teaser for the WP8 game we are building:

Getting Started

- Create a new Project: File –> New Project
image

- Welcome to your new environment:
image

- First thing you should do is hit File –> Save and save your current scene in the Assets folder. That folder is where you will keep all your scripts, models, materials, and furry kittens.

- The default view is fine, but I find it very useful to have the Scene pane and the Game pane side-by-side which will let you see what your camera sees while designing your scene. So click and drag the Scene tab directly down about an inch until your see this:
image

- After releasing the mouse you will get this side-by-side view:
image

- The Hierarchy pane on the left is where all the objects of the scene will be. Currently there is just the default camera. Let’s go ahead and create a cube by clicking [top menus] GameObject –> Create Other –> Cube. Now with the cube selected in the Hierarchy pane, click the resize button just above.
image

-If you’ve ever used a 3D modeling app you will feel right at home with the manipulation tools. In the Scene pane, click and drag the center block (which will resize the cube equally on X, Y, and Z) until the cube is a bit bigger. Notice how it grows in the Game pane too.
image

- You can move objects in a similar way by clicking on the Translate button (two to the left of Resize used earlier).
image

-Before building up the rest of the objects you should get used to controlling the view in the Scene pane. Remember that this is just the view that you are designing with – the final game will see objects from the perspective of the Camera object. Here are a few ways to control your view:

  • Hold down middle mouse button and drag will pan around the scene.
  • Rolling the middle mouse button forward and back will zoom in and out.
  • Holding Alt + Left mouse button and dragging will rotate around.

- Now that you are an accomplished modeler, lets create a bunch more cubes, resize them, and move them, until you have something that resembles this next image. Each wall is a cube that has been squashed and/or stretched.
image

- Notice how ugly it looks in the Game pane? That’s because it has no material or pretty shader. Let’s grab a random texture off the interwebs to apply to these cubes. I got a free one here: http://www.chrislanephoto.com/blog/tag/cement/ – but I first resized the texture to 256px X 256px. When you have a suitable image on your PC, in the bottom Project pane, Right Click –> Import New Asset and find the image.
image

- Apply that texture to each cube by dragging it from the bottom onto the cubes either in the Scene pane, or their names in the Hierarchy pane.
image

- That still isn’t very pretty. So let’s add some lighting. At the top click GameObject –> Create Other –> Directional Light. The default angle of the light works fine for me, but you can rotate it to get what you want. You can think of a Directional Light as the sun, so position doesn’t matter, only the angle at which it shines.
image

- We need a ball now, so create one with GameObject –> Create Other –> Sphere. Make it big enough to see easily, and position it roughly in the middle of the walls – most importantly make sure that it is in the right place depth-wise (as in distance to the camera).
image

- We want this ball to bounce off the walls. This would usually be a rather complicated affair, except of course, with Unity3D. Select the sphere, then in the Inspector pane on the right click Add Component –> Physics –> Rigid Body.
image

- Clicking Play (at the top) at this point will have the ball just dropping down and resting on the bottom wall. Firstly, we don’t want gravity, so deselect the Gravity checkbox in the Inspector. Next, we want the sphere to be bouncy, so we need to create a new Physic Material for it. Right click in the Project pane at the bottom –> Create –> Physic Material and name it whatever you want. Now drag it from the bottom onto your sphere.

- To create some initial movement for the sphere lets give it some code. Right click in Project pane –> Create –> C# Script. Double-click on the resulting file which will open up the code in your default editor. Stick this line of code into the Start() method then save:
transform.rigidbody.AddRelativeForce(-2000f, -2000f, 0);

- Go back to Unity3D, and drag the script onto the sphere. Clicking Play will have the ball bouncing a bit but slowing down. So select the Physic Material you created earlier in the Project pane, and then in the Inspector pane set these values:

  • Dynamic Friction to 0
  • Static Friction to 0
  • Bounciness to 1
  • Bounce Combine to Maximum

- This will make it quite a bit bouncier, but it will still slow down. So drag the Physic Material over each wall, making them “bouncy” too. Now hit Play and the sphere should continually bounce around contently.

- Just to add some kitsch, lets add a smoke trail to the sphere. In the top menu hit Assets –> Import New Package –> Particles then click Import on the dialog that comes up. This will import the whole package – which you don’t need – but it’s fine for now. If you open up a different program when Unity3D has a dialog open it disappears – you will need to Alt+Tab back to get the dialog back.

- In the Project pane at the bottom navigate to the Smoke folder.
image

- Drag Smoke Trail onto the sphere which will make it a child. Then with it selected, change the value of Min Emission and Max Emission to 200 in the Inspector pane to make it easier to see.
image

- Hit Play and you should have a smoke trail.
image

 

Interacting with Windows Phone

A rather cool side-effect of how Unity3D creates a Windows Phone project is that your game ends up as a class library rendering to a XAML panel. This means that you have direct access in code to all your Unity3D script classes. So let’s assume that there was no way in Unity3D to make Windows Phone vibrate – we can create an event in a script, and then sign up to that event in the Windows Phone project code and call the vibrate API.

You’re a Unity3D expert by now, so I will be moving faster.

- We need a static class that the event will be in. Create a new C# script in the Assets folder and open it up. I called mine StaticInterop. Clear the code that was generated so you just have this:

using UnityEngine;
using System.Collections;
using System;
public class StaticInterop { }

- Now add this code and save:
public class StaticInterop {
public static event EventHandler VibrateMe;

    public static void FireVibrateMe()
{
if (VibrateMe != null)
{
VibrateMe(null, null);
}
}
}

- So that’s just a little helper to fire an event. Next we need to fire the event every time the sphere hits a wall. So open up the script you applied to the sphere earlier and add this method which will automatically get called when the body collides with something:
void OnCollisionEnter(Collision collision) {
StaticInterop.FireVibrateMe();
}

- That’s all the Unity3D stuff done, so lets export this out. Make sure your scene and all files are saved. Click File –> Build Settings, select Windows Phone 8, then Add Current. Then to export it press Build at the bottom. You can create a new folder for it to export to.
image

- When it’s finished the root folder will popup. Go into the folder that you chose to export to and open up the solution. At this stage you can plug your WP8 device in and run the project.
image

- Let’s now add some vibration! In MainPage.xaml.cs make a class variable for the Vibration API (this will need using Microsoft.Devices):
VibrateController vibrator = VibrateController.Default;

- Sign up to that event (we created earlier) on the last line of the DrawingSurface_Loaded method:
StaticInterop.VibrateMe += StaticInterop_VibrateMe;

- And add the event handler code:
void StaticInterop_VibrateMe(object sender, EventArgs e)
{
vibrator.Start(new TimeSpan(0, 0, 0, 0, 20));
}

 

Running the project on your Windows Phone will now have a little ball bouncing around with a smoke trail, and the phone will vibrate for 20ms every time a wall is hit.

Hopefully this has helped a few Windows Phone devs getting started in the Unity3D world.

Thanks a lot to the guys at MonkeyMoon and CodingJar who helped me with all my little problems at AppCademy. Checkout their games using Unity3D on WP8!

If you’ve got question you can ask me here or on the Twitter machine: @roguecode

TwitterFacebookRedditGoogle+EmailPinterest
  • http://www.robodance.com/ roschler

    Excellent tutorial Matt. Will you be using Unity3D for your AppCampus app “Angry Llamas”?

    • RogueCode

      Yup, we are :-)

      • http://www.robodance.com/ roschler

        Great. Nothing like a finely detailed Vicious Llama coming to bite your face off! :)

  • http://twitter.com/on_code Laurent Victorino

    It seems that you don’t need help with Unity anymore :) Nice tutorial mate.

  • http://www.facebook.com/mikaelthomsen.dk Mikael Thomsen

    Thanks Matt. Great tutorial!

  • http://darkgenesis.zenithmoon.com/ Simon (darkside) J

    Nice and easy to follow tutorial Matt, however doesn’t this breach the Unity NDA for the Windows phone (and Windows 8) beta?.
    Been so tempted to do a few articles like this but was advised not to.

    • RogueCode

      Thanks! I double checked again with the Unity guys and they said that this post is perfectly fine.

  • Hamish Willee

    This is a really good tutorial and should have lifetime greater than the average blog post. Any chance we could “Syndicate” it as an article on the Nokia Developer Wiki? http://www.developer.nokia.com/Community/Wiki/Portal:Windows_Phone

    If so, all you’d have to do is create the article name (so you get recognition), copy-paste in the text, and I’d do all the formatting and adjustment to wiki style (would also cross link back here of course).

    • RogueCode

      Thanks, sounds good.

      • http://www.robodance.com/ roschler

        I knew you were with the Syndicate! :)

  • shiroryu

    Those of you who tried the beta of Unity for Windows Store, is it possible when choosing the XAML visual studio project template to overlay a XAML GUI over the Unity viewport ? Indeed, I would like to have a 2D XAML GUI for my Unity application.

    • shiroryu

      Unity 4.2 is out now and I can answer to my question : yes you can !

      • RogueCode

        Sorry about that – thought I had replied!
        So yeah you can, but careful with regards to performance.

  • Raajit Sharma

    love the tutorial helped me alot, can you do one on how to get accelerometer inputs into unity 3d projects?

    • RogueCode

      As far as I am aware, Unity 3D actually supports the accelerometer internally. Someone did actually ask me the same thing recently. Checkout the conversation here, maybe it will help too: https://twitter.com/matthiasshap/status/363043751100301312
      Let me know if you don’t come right.

  • regeter

    I am not on Windows8, I had someone else on Windows 8 build a project in unity for Windows Phone 8. I got the resulting zip file. Am I correct that on step “- When it’s finished the root folder will popup. Go into the folder that
    you chose to export to and open up the solution. At this stage you can
    plug your WP8 device in and run the project.” i would need windows 8 again? Because my Visual studio 2012 complains that it doesn’t know this type.

    • RogueCode

      Yes, unfortunately you have to have Windows 8 :(
      On the plus side, you may start enjoying W8 more than 7 after a few weeks (I did).
      Maybe you could run it in a VM? (Although I’m not 100% sure if you would still be able to deploy to an actual device).

  • Veera Murthy

    Error 1 The type or namespace name ‘UnityPlayer’ could not be
    found (are you missing a using directive or an assembly reference?)
    C:UsersDG150DesktopmurthyunitygamesSample_4.2win8SampleMainPage.xaml.cs
    17 18 Sample

    Error 2 The type or namespace name
    ‘WinRTBridge’ could not be found (are you missing a using directive or
    an assembly reference?)
    C:UsersDG150DesktopmurthyunitygamesSample_4.2win8SampleMainPage.xaml.cs
    18 21 Sample

    Error 3 The name ‘UnityPlayer’ does not
    exist in the current context
    C:UsersDG150DesktopmurthyunitygamesSample_4.2win8SampleMainPage.xaml.cs
    49 5 Sample2

    hiii i tried with one sample game so i am getting these types of errors i didn’t add any code from visual studio side

    what should i doo??

    i have unity 4.0 , windows 8 os, phone sdk, emulator, hyper v is enabled, .net frame work 4.5 .

    even i tried to add the references it showing the following message

    “a reference to a higher version or incompatible assembly cannot be added to the project”

    how to fix these bugs please help me out….!!!!!!!!!!!!!!!

    • RogueCode

      You mention that you haven’t added any code on the VS side, but those errors specifically mention code in MainPage.xaml.cs – so maybe the sample you are using has some code there.

      Either way, did you run through the tutorial above? If not, maybe try that and see if it all works.

  • Ravindra Kumbhar

    Does Unity 4.2 support x64 Windows Store applications?

    When I build my Windows Store application (created in Unity 4.2) in Visual Studio 2012 and choose x86 or ARM platform everything works fine, but when I try to build x64 the player folder (and DLL references) is missing.

    Is it a problem with my installation or does Unity not support x64 Windows Store applications?

    Please help me out . Thanks in advance