Ill get into real game development with Unity in the next article, but, first, Ill explore the Unity intece, project structure and architecture.
Ill assign some code to a new GameObject, in this case a cube you can create via GameObject Create Other Cube. I renamed the cube Enemy and then created another to have two cubes. You can see inFigure I moved one cube about units away from the other, which you can do by using the move tool on the or the W key once an object is highlighted.
Now that youve seen what projects get created, Ill explore the folders that trigger these projects and show you what their purposes are. Every folder path assumes its underneath the /Assets root folder in your project view. Assets is always the root folder and contains all of your asset files underneath it. For example, Standard Assets is actually /Assets/Standard Assets. The build process for your scripts runs through four phases to generate assemblies. Objects compiled in Phase cant see those in Phase because they havent yet been compiled. This is important to know when youre mixing UnityScript and C in the same project. If you want to reference a C class from UnityScript, you need to make sure it compiles in an earlier phase.
Designing a game in Unity is a irly straightforward process
Were sorry. The content you requested has been removed. Youll be auto redirected in second.
Start This method is called during the first frame of the objects lifetime but before any Update methods. It may seem very similar to Awake, but with Start, you know the other objects have been initialized via Awake and exist in your scene and, therefore, you can query other objects in code easily, like so
After you edit code in MonoDevelop or your code editor of choice and then switch back to Unity, youll typically notice a short delay. This is because Unity is compiling your code. You can change your code editor not debugger via Edit Preferences External Tools External Script Editor. Any compilation issues will show up at the very bottom status bar of your Unity Editor screen, so keep an eye out for them. If you try to run your game with errors in the code, Unity wont let you continue.
Update This method is called every frame. How often is that, you ask? Well, it varies. Its completely computationdependent. Because your system is always changing its load as it renders different things, this frame rate varies every second. You can press the Stats button in the Game when you go into play mode to see your current frame rate, as shown inFigure .
A GameObject has a Name, a Tag similar to a tag youd assign via a FrameworkElement.Tag in XAML or a tag in Windows Forms, a Layer and the Transform probably the most important property of all.
Once you have code in your project, Unity creates one or more project files in your root folder which isnt visible in the Unity intece. These are not the Unity engine binaries, but instead the projects for Visual Studio or MonoDevelop in which youll edit and compile your code. Unity can create what might seem like a lot of separate projects, asFigure shows, although each one has a an important purpose.
Continuing with the Unity intece, Ill go forward from clicking Create in the dialog inFigure so a new project is created. The deult Unity window layout is shown inFigure 3.
Figure The Enemy with a Script Assigned to It
Unity Developing Your First Game with Unity and C
Phase consists of all remaining scripts those inside any other folder called Editor, such as /Assets/Editor or /Assets/Foo/Editor. This phase creates the AssemblyCSharp.csproj project.
When you open Unity for the first time, you see the project dialog shown inFigure .
public class EnemyHealth MonoBehavior private EnemyAI _enemyAI; // Use this for initialization. void Start // Get a ref to the EnemyAI script component on this game object. var enemyAI this.GetComponent
Typically, Unity opens the last scene youve been working on, although sometimes when Unity opens a project it creates a new empty scene and you have to go find the scene in your project explorer. This can be pretty confusing for new users, but its important to remember if you happen to open up your last project and wonder where all your work went! Relax, youll find the work in a scene file you saved in your project. You can search for all the scenes in your project by clicking the icon indicated inFigure and filtering on Scene.
Of important mention is the Game next to the Scene . This activates when you click play and your game starts to run in this window. This is called play mode and it gives you a playground for testing your game, and even allows you to make live changes to the game by switching back to the Scene . Be very careful here, though. While the play button is highlighted, youre in play mode and when you leave it, any changes you made while in play mode will be lost. I, along with just about every Unity developer Ive ever spoken with, have lost work this way, so I change my Editors to make it obvious when Im in play mode via Edit Preferences Colors Playmode tint.
In the project dialog, you specify the name and location for your project . You can import any packages into your project , though you dont have to check anything off here; the list is provided only as a convenience. You can also import a package later. A package is a .unitypackage file that contains prepackaged resourcesmodels, code, scenes, pluginsanything in Unity you can package upand you can reuse or distribute them easily. Dont check something off here if you dont know what it is, though; your project will grow, sometimes considerably. Finally, you can choose either D or 3D 3. This dropdown is relatively new to Unity, which didnt have significant D game tooling until irly recently. When set to 3D, the deults vor a 3D projecttypical Unity behavior as its been for ages, so it doesnt need any special mention. When D is chosen, Unity changes a few seemingly smallbut majorthings, which Ill cover in the D article later in this series.
As a software architect, Ive written many systems, reverseengineered native code malware, and generally could figure things out on the code side. When it came to games, though, I was a bit lost as to where to start. I had done some native code graphics programming in the early Windows days, and it wasnt a fun experience. I then started on DirectX development but realized that, although it was extremely powerful, it seemed like too much code for what I wanted to do.
Doing things per frame involves a slightly different way of thinking than saying move to this point. For this example, Im going to move the object a little bit every frame so I have exact control over where it moves. If youd rather not adjust every frame, there are libraries to do single function call movements, such as the freely available iTween library.
In game development, its quite common to use vectors, which Ill cover a bit more in future articles. For now, its sufficient to know that Transform.Position and Transform.Scale are both Vector3 objects. A Vector3 is simply a threedimensional vector; in other words, its nothing more than three pointsjust X, Y and Z. Through these three values, you can set an objects location and even move an object in the direction of a vector.
A GameObject is pretty as it pertains to the Inspector window. You can see inFigure that an empty GameObject was added to the scene; note its properties in the Inspector. GameObjects by deult have no visual properties except the widget Unity shows when you highlight the object. At this point, its simply a irly empty object.
When you perform a build for Windows, Unity is responsible for the calls to generate the game libraries from your C/UnityScript/Boo code DLLs and to include its native runtime libraries. For Windows Store and Windows Phone , it will export a Visual Studio solution, except for Windows standalone, in which Unity generates the .exe and required .dll files. Ill discuss the various build s in the final article in the series, when I cover building for the platform. The graphics rendering at a low level is performed on the Windows platforms by DirectX.
There are a couple other lessused folders that arent covered here, such as Resources. And there is the pending question of what the compiler is using. Is it .NET? Is it Mono? Is it .NET for the Windows Runtime WinRT? Is it .NET for Windows Phone Runtime?Figure lists the deults used for compilation. This is important to know, especially for WinRTbased applications because the APIs available per platform vary.
This article serves as an overview of the architecture and process in Unity. I covered the intece, basics of assigning code, GameObjects, components, Mono and .NET, plus more. This sets us up nicely for the next article where Ill e right into assembling game components for a D game. Keep an eye on Microsoft Virtual Academy, as Ill be doing a twoday Unity learning event late summer. And watch for local regional learning events atunity3d/s/windows/events.
Awake This method is called once per object when the object is first initialized. Other components may not yet be initialized, so this method is typically used to initialize the current GameObject. You should always use this method to initialize a MonoBehaviorderived class, not a constructor. And dont try to query for other objects in your scene here, as they may not be initialized yet.
Console This window can become somewhat hidden, but it shows output from your compile, errors, warnings and so forth. It also shows debug messages from code; for example, Debug.Log will show its output here.
// Returns the first EnemyAI script component instance it finds on any game object. // This is EnemyAI a component, not a GameObject. var enemyAI GameObject.FindObjectOfType
I want to stress the importance of changes only through the Unity intece and not the file system directly. This includes even copy and paste. Unity tracks metadata for your objects through the editor, so use the editor to make changes outside of a few fringe cases. You can drag and drop from your file system into Unity, though; that works just fine.
The Assets folder contains all your assetsart, code, audio; every single file you bring into your project goes here. This is always the toplevel folder in the Unity Editor. But make changes only in the Unity intece, never through the file system.
Phase scripts are in the Standard Assets/Editor, Pro Standard Assets/Editor and Plugins/Editor folders. The last folder is meant for scripts that interact with the Unity Editor API for designtime functionality think of a Visual Studio plugin and how it enhances the GUI, only this runs in the Unity Editor. This phase creates the AssemblyCSharpEditorfirstpass.csproj project.
Unity lets you test your game in the IDE without having to perform any kind of export or build. When you run code in Unity, youre using Mono version 3., which has API compatibility roughly on par with that of the .NET Framework 3./CLR ..
To debug, you launch MonoDevelop from Unity. MonoDevelop has a plugin that opens a connection back to the Unity debugger and issues commands to it after you Debug Attach to Process in MonoDevelop. With UnityVS, you connect the Visual Studio debugger back to Unity instead.
FixedUpdate This method is called a fixed number of times a second, independent of the frame rate. Because Update is called a varying number of times a second and isnt in sync with the physics engine, its typically best to use FixedUpdate when you want to provide a force or some other physicsrelated functions on an object. FixedUpdate by deult is called every . seconds, meaning Unity also performs physics calculations every . seconds this interval is called the Fixed Timestep and is developeradjusle, which, again, is independent of frame rate.
Unity Developing Your First Game with Unity and C
Project All the files in your project. You can drag and drop from Explorer into Unity to add files to your project.
In code, I can get a reference to any component exposed in the editor. I can also assign scripts to a GameObject, each with its own Start and Update methods and many other methods. Assuming a script component containing this code needs a reference to the EnemyAI class component, I can simply ask for that component
Everything that runs in your game exists in a scene. When you package your game for a platform, the resulting game is a collection of one or more scenes, plus any platformdependent code you add. You can have as many scenes as you want in a project. A scene can be thought of as a level in a game, though you can have multiple levels in one scene file by just moving the player/camera to different points in the scene. When you download thirdparty packages or even sample games from the asset store, you typically must look for the scene files in your project to open. A scene file is a single file that contains all sorts of metadata about the resources used in the project for the current scene and its properties. Its important to save a scene often by pressing CtrlS during development, just as with any other tool.
The code is a class that finds a player and moves its owner toward it. You typically do movement operations via one of two approaches Either you move an object to a new position every frame by changing its Transform.Position properties, or you apply a physics force to it and let Unity take care of the rest.
You edit your code in Unity by doubleclicking on a code file in the project view, which opens the deult crossplatform editor, MonoDevelop. If you prefer, you can configure Visual Studio as your editor.
public class EnemyAI MonoBehavior // These values will appear in the editor, full properties will not. public float Speed private Transform _playerTransform; private Transform _ myTransform; // Called on startup of the GameObject its assigned to. void Start // Find some gameobject that has the tag Player assigned to it. // This is startup code, shouldnt query the player object every // frame. Store a ref to it. var player GameObject.FindGameObjectWithTagPlayer; if !player Debug.LogError Could not find the main player. Ensure it has the player tag set.; else // Grab a reference to its transform for use later saves on managed // code to native code calls. _playerTransform player.transform; // Grab a reference to our transform for use later. _myTransform this.transform; // Called every frame. The frame rate varies every second. void Update // I am setting how st I should move toward the player // per second. In Unity, one unit is a meter. // TimeltaTime gives the amount of time since the last frame. // If youre running FPS frames per second this is / ., // so w/Speed and frame rate of FPS frame rate always varies // per second, I have a movement amount of *. .33 units // per frame. This is units. var moveAmount Speed * TimeltaTime; // Update the position, move toward the players position by moveAmount. _myTransform.position Vector3.MoveTowards_myTransform.position, _playerTransform.position, moveAmount;
You debug with MonoDevelop or use a thirdparty plugin for Visual Studio, UnityVS. You cant use Visual Studio as a debugger without UnityVS because when you debug your game, you arent debugging Unity.exe, youre debugging a virtual environment inside of Unity, using a soft debugger thats issued commands and performs actions.
Unity is a D/3D engine and framework that gives you a system for designing game or app scenes for D, .D and 3D. I say games and apps because Ive seen not just games, but training simulators, firstresponder applications, and other businessfocused applications developed with Unity that need to interact with D/3D space. Unity allows you to interact with them via not only code, but also visual components, and export them to every major mobile platform and a whole lot morefor free. Theres also a pro version thats very nice, but it isnt free. You can do an impressive amount with the free version. Unity supports all major 3D applications and many audio formats, and even understands the Photoshop .psd format so you can just drop a .psd file into a Unity project. Unity allows you to import and assemble assets, write code to interact with your objects, create or import animations for use with an advanced animation system, and much more.
In a scene, you cant see anything without a camera and you cant hear anything without an Audio Listener component attached to some GameObject. Notice, however, that in any new scene, Unity always creates a camera that has an Audio Listener component already on it.
This list is populated from .unitypackage files in certain locations on your system; Unity provides a handful on install. Anything you download from the Unity asset store also comes as a .unitypackage file and is cached locally on your system in CUsersyouAppDataRoamingUnityAsset Store. As such, it will show up in this list once it exists on your system. You could just doubleclick on any .unitypackage file and it would be imported into your project.
Take a look at the code inFigure and note the public variable. If you look in the Editor, you can see that my public variable appears with an option to override the deult values at run time. This is pretty cool. You can change deults in the GUI for primitive s, and you can also expose public variables not properties, though of many different object s. If I drag and drop this code onto another GameObject, a completely separate instance of that code component gets instantiated. This is a basic example and it can be made more efficient by, say, adding a RigidBody component to this object, but Ill keep it here.
Perhaps the most powerful part of Unity is the Unity Asset Store, arguably the best asset marketplace in the gaming market. In it you can find all of your game component needs, such as artwork, 3D models, animation files for your 3D models see Mixamos content in the store for more than , motions, audio effects and full tracks, pluginsincluding those like the MultiPlatform toolkit that can help with multiple platform supportvisual scripting systems such as PlayMaker and Behave, advanced shaders, ures, particle effects, and more. The Unity intece is fully scriple, allowing many thirdparty plugins to integrate right into the Unity GUI. Most, if not all, professional game developers use a number of packages from the asset store, and if you have something decent to offer, you can publish it there as well.
In the prior code example, there are two methods, Start and Update, and the class EnemyHealth inherits from the MonoBehavior base class, which lets you simply assign that class to a GameObject. Theres a lot of functionality in that base class youll use, and typically a few methods and properties. The main methods are those Unity will call if they exist in your class. There are a handful of methods that can get called seebit.ly/jeA3UM. Though there are many methods, just as with the ASP.NET Web Forms Page Lifecycle, you typically use only a few. Here are the most common code methods to implement in your classes, which relate to the sequence of events for MonoBehaviorderived classes
Hierarchy All the game objects in the scene. Note the use of the term GameObjects and the GameObjects dropdown menu.
The first thing I do is rightclick in the Project window to create a new C script called EnemyAI. To assign this script to an object, I simply drag the script file from the project view to the object in the Scene view or the Hierarchy and the code is assigned to the object. Unity takes care of the rest. Its that easy.
Then, one day, I decided to experiment with Unity, and I saw it could do some amazing things. This is the first article in a fourpart series that will cover the basics and architecture of Unity. Ill show how to create D and 3D games and, finally, how to build for the Windows platforms.
Figure shows the Enemy cube with the script assigned to it.
Inspector The components properties of the selected object in the scene.
Receive the MSDN Flash email newsletter every other week, with news and information personalized to your interests and areas of focus.
Where does Microsoft fit into this? Microsoft and Unity work closely together to ensure great platform support across the Microsoft stack. Unity supports Windows standalone execules, Windows Phone, Windows Store applications, Xbox 3 and Xbox One.
I hesitate to describe anything Unity isnt as people challenge that all the time. However, Unity by deult isnt a system in which to design your D assets and 3D models except for terrains. You can bring a bunch of zombies into a scene and control them, but you wouldnt create zombies in the Unity deult tooling. In that sense, Unity isnt an assetcreation tool like Autodesk Maya or 3DSMax, Blender or even Adobe Photoshop. Theres at least one thirdparty modeling plugin ProBuilder, though, that allows you to model 3D components right inside of Unity; there are D world builder plugins such as the D Terrain Editor for creating D tiled environments, and you can also design terrains from within Unity using their Terrain Tools to create amazing landscapes with trees, grass, mountains, and more. So, again, I hesitate to suggest any limits on what Unity can do.
For each of those projects, theres a duplicate project created with vs appended to it, AssemblyCSharpvs.csproj, for example. These projects are used if Visual Studio is your code editor and they can be added to your exported project from Unity for platformspecific debugging in your Visual Studio solution.
Unity projects arent like Visual Studio projects. You dont open a project file or even a solution file, because it doesnt exist. You point Unity to a folder structure and it opens the folder as a project. Projects contain Assets, Library, ProjectSettings, and Temp folders, but the only one that shows up in the intece is the Assets folder, which you can see inFigure .
Thanks to the following technical experts for reviewing this article Matt Newman Subscience Studios, Jaime Rodriguez Microsoft and Tautvydas Žilys Unity
Phase 3 comprises all other scripts that arent inside an Editor folder. This phase creates the AssemblyCSharpEditor.csproj project.
Phase consists of runtime scripts in the Standard Assets, Pro Standard Assets and Plugins folders, all located under/Assets. This phase creates the AssemblyCSharpfirstpass.csproj project.
Adam Tuliperis a senior technical evangelist with Microsoft living in sunny Southern California. Hes an indie game dev, coadmin of the Orange County Unity Meetup, and apluralsightauthor. He and his wife are about to have their third child, so reach out to him while he still has a spare moment r on Twitter attwitter/AdamTuliper.
Bring in your assets artwork, audio and so on. Use the asset store. Write your own. Hire an artist. Note that Unity does have native support for Maya, Cheetah3d, Blender and 3dsMax, in some cases requiring that software be installed to work with those native 3D formats, and it works with .obj and .fbx common file formats, as well.
AsFigure indicates, Unity has done work to ensure crossplatform support, and you can change platforms literally with one click, although to be ir, theres typically some minimal effort required, such as integrating with each store for inapp purchases.
; // Ill actually get a ref to its toplevel GameObject. var enemyGameObject enemyAI.gameObject; // Want the enemys position? var position enemyGameObject.transform.position;
Download the latest version of Unity and get yourself a twobutton mouse with a clickable scroll wheel. Theres a single download that can be licensed for free mode or pro. You can see the differences between the versions /unity/licenses. The Editor, which is the main Unity intece, runs on Windows including Suce Pro, Linux and OS X.
You add functionality to GameObjects by adding Components. Everything you add is a Component and they all show up in the Inspector window. There are MeshRender and SpriteRender Components; Components for audio and camera functionality; physicsrelated Components colliders and rigidbodies, particle systems, pathfinding systems, thirdparty custom Components, and more. You use a script Component to assign code to an object. Components are what bring your GameObjects to life by adding functionality, akin to thedecorator pattern in software development, only much cooler.
The Library folder is the local cache for imported assets; it holds all metadata for assets. The ProjectSettings folder stores settings you configure from Edit Project Settings. The Temp folder is used for temporary files from Mono and Unity during the build process.
Virtually everything in your scene is a GameObject. Think of System.Object in the .NET Framework. Almost all s derive from it. The same concept goes for GameObject. Its the base class for all objects in your Unity scene. All of the objects shown inFigure and many more derive from a GameObject.
The Transform property is simply the position, rotation and scale of any GameObject. Unity uses the lefthand coordinate system, in which you think of the coordinates of your computer screen as X horizontal, Y vertical and Z depth, that is, coming in or going out of the screen.
If you have a Unity project, you wont see all of these files. They get created only when you have code put into various special folders. The projects shown inFigure are broken out by only three s
Toolbar To the r left are Pan, Move, Rotate, Scale and in the center Play, Pause, Advance Frame. Clicking Play plays the game near instantly without having to perform separate builds. Pause pauses the game, and advance frame runs it one frame at a time, giving you very tight debugging control.
; // Update is called once per frame. void Update _enemyAI.MoveTowardsPlayer; Unity Developingunity 3d games Your First Game with Unity and C