Detect When Application Gets Focus Again Unity
This browser is no longer supported.
Upgrade to Microsoft Border to have advantage of the latest features, security updates, and technical support.
Baronial 2014
Volume 29 Number 8
Unity : Developing Your First Game with Unity and C#
Adam Tuliper
As a software architect, I've written many systems, contrary-engineered native code malware, and more often than not could figure things out on the lawmaking side. When it came to making games, though, I was a bit lost as to where to kickoff. I had done some native code graphics programming in the early on Windows days, and it wasn't a fun experience. I and then started on DirectX development just realized that, although it was extremely powerful, it seemed similar too much code for what I wanted to practice.
Then, one twenty-four hour period, I decided to experiment with Unity, and I saw it could do some amazing things. This is the first commodity in a four-office serial that will cover the basics and architecture of Unity. I'll evidence how to create 2D and 3D games and, finally, how to build for the Windows platforms.
What Unity Is
Unity is a 2D/3D engine and framework that gives y'all a system for designing game or app scenes for 2d, 2.5D and 3D. I say games and apps because I've seen not simply games, simply training simulators, first-responder applications, and other business concern-focused applications developed with Unity that need to interact with 2d/3D space. Unity allows you to interact with them via not only code, but too visual components, and export them to every major mobile platform and a whole lot more—for free. (There'due south besides a pro version that's very overnice, only it isn't complimentary. Yous can practise an impressive amount with the free version.) Unity supports all major 3D applications and many sound formats, and fifty-fifty understands the Photoshop .psd format so you can only driblet a .psd file into a Unity project. Unity allows you to import and get together avails, write code to collaborate with your objects, create or import animations for use with an advanced blitheness organisation, and much more.
Every bit Figure 1 indicates, Unity has done work to ensure cross-platform support, and you lot can alter platforms literally with one click, although to be off-white, there's typically some minimal effort required, such as integrating with each store for in-app purchases.
Figure one Platforms Supported by Unity
Mayhap the nearly powerful part of Unity is the Unity Asset Store, arguably the all-time asset marketplace in the gaming market. In it y'all tin can observe all of your game component needs, such as artwork, 3D models, animation files for your 3D models (come across Mixamo'south content in the store for more than 10,000 motions), audio effects and full tracks, plug-ins—including those like the MultiPlatform toolkit that tin aid with multiple platform support—visual scripting systems such as PlayMaker and Conduct, advanced shaders, textures, particle effects, and more than. The Unity interface is fully scriptable, assuasive many third-party plug-ins to integrate right into the Unity GUI. Near, if not all, professional game developers use a number of packages from the asset store, and if yous accept something decent to offer, you can publish it there besides.
What Unity Isn't
I hesitate to describe anything Unity isn't as people challenge that all the fourth dimension. Even so, Unity past default isn't a system in which to design your 2D avails and 3D models (except for terrains). Y'all can bring a bunch of zombies into a scene and control them, but you wouldn't create zombies in the Unity default tooling. In that sense, Unity isn't an nugget-creation tool similar Autodesk Maya or 3DSMax, Blender or even Adobe Photoshop. There'southward at least 1 third-political party modeling plug-in (ProBuilder), though, that allows you to model 3D components correct within of Unity; at that place are 2nd world builder plug-ins such as the 2D Terrain Editor for creating 2nd tiled environments, and y'all tin can also design terrains from within Unity using their Terrain Tools to create amazing landscapes with trees, grass, mountains, and more. So, once again, I hesitate to suggest any limits on what Unity can do.
Where does Microsoft fit into this? Microsoft and Unity work closely together to ensure great platform support beyond the Microsoft stack. Unity supports Windows standalone executables, Windows Telephone, Windows Store applications, Xbox 360 and Xbox 1.
Getting Started
Download the latest version of Unity and become yourself a two-push mouse with a clickable curl wheel. There'south a single download that can be licensed for costless mode or pro. Y'all can run into the differences betwixt the versions at unity3d.com/unity/licenses. The Editor, which is the main Unity interface, runs on Windows (including Surface Pro), Linux and Os Ten.
I'll get into real game development with Unity in the next commodity, but, first, I'll explore the Unity interface, projection structure and compages.
Architecture and Compilation
Unity is a native C++-based game engine. You write lawmaking in C#, JavaScript (UnityScript) or, less often, Boo. Your code, not the Unity engine lawmaking, runs on Mono or the Microsoft .Net Framework, which is Simply-in-Time (JIT) compiled (except for iOS, which doesn't let JIT code and is compiled past Mono to native code using Ahead-of-Time [AOT] compilation).
Unity lets you test your game in the IDE without having to perform whatsoever kind of export or build. When you run lawmaking in Unity, you're using Mono version iii.5, which has API compatibility roughly on par with that of the .NET Framework 3.5/CLR two.0.
You lot edit your code in Unity past double-clicking on a code file in the project view, which opens the default cantankerous-platform editor, MonoDevelop. If you prefer, you can configure Visual Studio as your editor.
You debug with MonoDevelop or apply a 3rd-party plug-in for Visual Studio, UnityVS. You can't use Visual Studio every bit a debugger without UnityVS because when yous debug your game, you aren't debugging Unity.exe, you're debugging a virtual environment inside of Unity, using a soft debugger that'due south issued commands and performs deportment.
To debug, you launch MonoDevelop from Unity. MonoDevelop has a plug-in that opens a connection dorsum to the Unity debugger and issues commands to information technology later on you Debug | Adhere to Process in MonoDevelop. With UnityVS, you connect the Visual Studio debugger dorsum to Unity instead.
When yous open up Unity for the first time, you come across the projection dialog shown in Figure 2.
Figure ii The Unity Project Wizard
In the projection dialog, y'all specify the name and location for your project (1). You tin import whatsoever packages into your project (two), though yous don't take to check anything off here; the list is provided only as a convenience. You can also import a package afterwards. A package is a .unitypackage file that contains prepackaged resources—models, code, scenes, plug-ins—anything in Unity y'all tin package up—and you can reuse or distribute them easily. Don't check something off here if you don't know what it is, though; your project size will grow, sometimes considerably. Finally, you tin choose either 2D or 3D (iii). This dropdown is relatively new to Unity, which didn't have meaning 2D game tooling until fairly recently. When set to 3D, the defaults favor a 3D project—typical Unity behavior every bit it'south been for ages, then it doesn't demand any special mention. When 2nd is chosen, Unity changes a few seemingly small—only major—things, which I'll encompass in the 2d article afterwards in this series.
This list is populated from .unitypackage files in sure locations on your system; Unity provides a scattering on install. Anything you download from the Unity nugget store also comes as a .unitypackage file and is buried locally on your system in C:\Users\<you lot>\AppData\Roaming\Unity\Asset Shop. Equally such, it volition prove up in this listing once information technology exists on your system. You lot could just double-click on whatever .unitypackage file and information technology would exist imported into your projection.
Continuing with the Unity interface, I'll become forward from clicking Create in the dialog in Figure 2 so a new projection is created. The default Unity window layout is shown in Figure iii.
Figure iii The Default Unity Window
Hither's what you'll see:
- Projection: All the files in your project. You can drag and drop from Explorer into Unity to add files to your project.
- Scene: The currently open scene.
- Hierarchy: All the game objects in the scene. Annotation the utilize of the term GameObjects and the GameObjects dropdown menu.
- Inspector: The components (properties) of the selected object in the scene.
- Toolbar: To the far left are Pan, Move, Rotate, Scale and in the eye Play, Pause, Advance Frame. Clicking Play plays the game about instantly without having to perform separate builds. Pause pauses the game, and advance frame runs information technology i frame at a fourth dimension, giving you very tight debugging command.
- Console: This window can become somewhat hidden, just information technology shows output from your compile, errors, warnings and and then along. Information technology besides shows debug messages from code; for example, Debug.Log will prove its output hither.
Of important mention is the Game tab adjacent to the Scene tab. This tab activates when y'all click play and your game starts to run in this window. This is chosen play way and information technology gives you lot a playground for testing your game, and even allows you to brand live changes to the game past switching back to the Scene tab. Be very conscientious here, though. While the play button is highlighted, y'all're in play fashion and when you leave information technology, whatever changes y'all fabricated while in play mode will be lost. I, along with just almost every Unity developer I've ever spoken with, have lost work this mode, so I modify my Editor's color to make it obvious when I'yard in play mode via Edit | Preferences | Colors | Playmode tint.
Almost Scenes
Everything that runs in your game exists in a scene. When y'all packet your game for a platform, the resulting game is a collection of ane or more scenes, plus any platform-dependent code y'all add together. Yous can have as many scenes as yous want in a projection. A scene can be thought of as a level in a game, though yous can take multiple levels in i scene file by just moving the histrion/camera to unlike points in the scene. When you download third-party packages or even sample games from the nugget store, you typically must look for the scene files in your project to open up. A scene file is a single file that contains all sorts of metadata nigh the resources used in the project for the current scene and its properties. It's important to salve a scene often by pressing Ctrl+Due south during development, merely as with any other tool.
Typically, Unity opens the last scene you've 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 information technology's important to remember if you happen to open up your last projection and wonder where all your work went! Relax, y'all'll detect the work in a scene file you saved in your project. Yous tin can search for all the scenes in your project by clicking the icon indicated in Figure 4 and filtering on Scene.
Figure 4 Filtering Scenes in the Project
In a scene, you can't see anything without a camera and y'all tin can't hear anything without an Audio Listener component attached to some GameObject. Notice, yet, that in whatever new scene, Unity e'er creates a camera that has an Audio Listener component already on it.
Project Structure and Importing Assets
Unity projects aren't similar Visual Studio projects. Yous don't open a project file or even a solution file, because it doesn't exist. You bespeak Unity to a folder structure and it opens the folder equally a project. Projects contain Assets, Library, ProjectSettings, and Temp folders, but the just one that shows upward in the interface is the Assets folder, which you can see in Figure 4.
The Assets folder contains all your assets—fine art, code, audio; every unmarried file you bring into your project goes here. This is always the top-level folder in the Unity Editor. But brand changes only in the Unity interface, never through the file organisation.
The Library folder is the local cache for imported assets; it holds all metadata for assets. The ProjectSettings binder stores settings you configure from Edit | Project Settings. The Temp folder is used for temporary files from Mono and Unity during the build process.
I want to stress the importance of making changes merely through the Unity interface and non the file organization directly. This includes fifty-fifty simple copy and paste. Unity tracks metadata for your objects through the editor, so utilise the editor to make changes (outside of a few fringe cases). You tin can drag and drop from your file organisation into Unity, though; that works just fine.
The All-Important GameObject
Virtually everything in your scene is a GameObject. Think of Organisation.Object in the .Cyberspace Framework. Almost all types derive from it. The same concept goes for GameObject. It's the base class for all objects in your Unity scene. All of the objects shown in Figure 5 (and many more) derive from a GameObject.
Effigy v GameObjects in Unity
A GameObject is pretty simple as it pertains to the Inspector window. Yous can run into in Figure half-dozen that an empty GameObject was added to the scene; note its backdrop in the Inspector. GameObjects by default take no visual properties except the widget Unity shows when you lot highlight the object. At this point, information technology'south just a fairly empty object.
Figure vi A Simple GameObject
A GameObject has a Name, a Tag (like to a text tag you'd 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).
The Transform belongings is simply the position, rotation and scale of any GameObject. Unity uses the left-manus coordinate system, in which you lot remember 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).
In game development, it's quite common to use vectors, which I'll comprehend a scrap more in future articles. For now, information technology's sufficient to know that Transform.Position and Transform.Scale are both Vector3 objects. A Vector3 is simply a three-dimensional vector; in other words, it'south nothing more than three points—simply X, Y and Z. Through these three uncomplicated values, you can set an object's location and fifty-fifty movement an object in the management of a vector.
Components
You add functionality to GameObjects by adding Components. Everything yous add is a Component and they all bear witness up in the Inspector window. There are MeshRender and SpriteRender Components; Components for audio and camera functionality; physics-related Components (colliders and rigidbodies), particle systems, path-finding systems, third-party custom Components, and more than. Yous use a script Component to assign lawmaking to an object. Components are what bring your GameObjects to life past adding functionality, akin to thedecorator pattern in software development, only much cooler.
I'll assign some code to a new GameObject, in this case a simple cube you can create via GameObject | Create Other | Cube. I renamed the cube Enemy and then created another to have two cubes. You lot can see in Figure 7 I moved i cube about -15 units abroad from the other, which you can practice by using the move tool on the toolbar or the W key once an object is highlighted.
Effigy 7 Electric current Project with Two Cubes
The code is a simple class that finds a player and moves its possessor toward it. You typically do movement operations via i of two approaches: Either you motility an object to a new position every frame by changing its Transform.Position properties, or yous utilise a physics force to it and permit Unity take care of the residue.
Doing things per frame involves a slightly different fashion of thinking than saying "motility to this point." For this instance, I'k going to move the object a little fleck every frame so I take verbal control over where it moves. If yous'd rather non suit every frame, there are libraries to exercise single function call movements, such as the freely bachelor iTween library.
The first thing I do is right-click in the Projection window to create a new C# script chosen EnemyAI. To assign this script to an object, I just drag the script file from the projection 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. Information technology's that easy.
Effigy 8 shows the Enemy cube with the script assigned to information technology.
Figure viii The Enemy with a Script Assigned to It
Have a look at the code in Figure 9 and note the public variable. If you lot look in the Editor, yous tin can meet that my public variable appears with an pick to override the default values at run fourth dimension. This is pretty absurd. You tin change defaults in the GUI for archaic types, and you tin also expose public variables (not properties, though) of many different object types. If I elevate and drib this code onto some other GameObject, a completely split up instance of that lawmaking component gets instantiated. This is a bones example and it can be fabricated more efficient past, say, calculation a RigidBody component to this object, but I'll keep it simple hither.
Figure 9 The EnemyAI Script
public class EnemyAI : MonoBehavior { // These values will appear in the editor, full properties will not. public float Speed = 50; private Transform _playerTransform; private Transform _ myTransform; // Called on startup of the GameObject it's assigned to. void Showtime() { // Find some gameobject that has the text tag "Player" assigned to it. // This is startup code, shouldn't query the player object every // frame. Store a ref to it. var player = GameObject.FindGameObjectWithTag("Role player"); if (!role player) { Debug.LogError( "Could non find the principal player. Ensure it has the player tag gear up."); } else { // Grab a reference to its transform for utilize later (saves on managed // lawmaking to native lawmaking calls). _playerTransform = role player.transform; } // Grab a reference to our transform for use later. _myTransform = this.transform; } // Chosen every frame. The frame rate varies every second. void Update() { // I am setting how fast I should movement toward the "player" // per second. In Unity, one unit is a meter. // Time.deltaTime gives the corporeality of fourth dimension since the last frame. // If you're running sixty FPS (frames per second) this is 1/60 = 0.0167, // and then w/Speed=2 and frame rate of 60 FPS (frame charge per unit always varies // per second), I have a motion amount of 2*0.0167 = .033 units // per frame. This is 2 units. var moveAmount = Speed * Time.deltaTime; // Update the position, move toward the thespian's position past moveAmount. _myTransform.position = Vector3.MoveTowards(_myTransform.position, _playerTransform.position, moveAmount); } }
In code, I can become a reference to any component exposed in the editor. I can also assign scripts to a GameObject, each with its ain Start and Update methods (and many other methods). Assuming a script component containing this code needs a reference to the EnemyAI class (component), I tin can simply ask for that component:
public form EnemyHealth : MonoBehavior individual EnemyAI _enemyAI; // Use this for initialization. void Start () { // Get a ref to the EnemyAI script component on this game object. var enemyAI = this.GetComponent<EnemyAI>(); } // Update is called in one case per frame. void Update () { _enemyAI.MoveTowardsPlayer(); }
Afterwards you edit code in MonoDevelop or your code editor of choice so switch back to Unity, you'll typically notice a short delay. This is because Unity is background compiling your code. You can change your code editor (non debugger) via Edit | Preferences | External Tools | External Script Editor. Any compilation issues will evidence up at the very bottom status bar of your Unity Editor screen, so keep an eye out for them. If you endeavor to run your game with errors in the code, Unity won't let you lot continue.
Writing Code
In the prior code example, there are two methods, Showtime and Update, and the class EnemyHealth inherits from the MonoBehavior base class, which lets you lot simply assign that form to a GameObject. There's a lot of functionality in that base class yous'll use, and typically a few methods and properties. The main methods are those Unity will call if they be in your course. At that place are a scattering of methods that tin get chosen (see bit.ly/1jeA3UM). Though at that place are many methods, merely equally with the ASP.Net Web Forms Page Lifecycle, yous typically utilise only a few. Here are the nigh mutual code methods to implement in your classes, which relate to the sequence of events for MonoBehavior-derived classes:
Awake: This method is called one time per object when the object is kickoff initialized. Other components may non nonetheless be initialized, and so this method is typically used to initialize the current GameObject. You should ever use this method to initialize a MonoBehavior-derived class, not a constructor. And don't endeavour to query for other objects in your scene here, as they may not be initialized notwithstanding.
Start: This method is chosen during the first frame of the object's lifetime merely before whatsoever Update methods. It may seem very like to Awake, only with Start, you lot know the other objects have been initialized via Awake and exist in your scene and, therefore, you can query other objects in code hands, similar so:
// Returns the start EnemyAI script component instance it finds on whatever game object. // This type is EnemyAI (a component), not a GameObject. var enemyAI = GameObject.FindObjectOfType<EnemyAI>(); // I'll actually go a ref to its top-level GameObject. var enemyGameObject = enemyAI.gameObject; // Want the enemy'southward position? var position = enemyGameObject.transform.position;
Update: This method is chosen every frame. How often is that, yous ask? Well, it varies. It'southward completely computation-dependent. Because your system is ever changing its load every bit information technology renders unlike things, this frame rate varies every second. Yous can press the Stats button in the Game tab when you go into play mode to see your current frame rate, as shown in Figure 10.
Figure 10 Getting Stats
FixedUpdate: This method is chosen a fixed number of times a second, independent of the frame rate. Considering Update is called a varying number of times a 2nd and isn't in sync with the physics engine, it's typically best to use FixedUpdate when you want to provide a force or another physics-related functions on an object. FixedUpdate by default is called every .02 seconds, significant Unity also performs physics calculations every .02 seconds (this interval is called the Fixed Timestep and is developer-adjustable), which, once again, is independent of frame rate.
Unity-Generated Code Projects
Once you have code in your projection, Unity creates one or more projection files in your root binder (which isn't visible in the Unity interface). These are not the Unity engine binaries, only instead the projects for Visual Studio or MonoDevelop in which you'll edit and compile your code. Unity tin can create what might seem like a lot of carve up projects, as Effigy 11 shows, although each one has a an important purpose.
Figure xi Unity-Created Projects
If you have a simple Unity project, you won't meet all of these files. They get created only when you have code put into various special folders. The projects shown in Figure 11 are broken out by simply three types:
- Assembly-CSharp.csproj
- Associates-CSharp-Editor.csproj
- Assembly-CSharp-firstpass.csproj
For each of those projects, there's a duplicate project created with -vs appended to it, Assembly-CSharp-vs.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 platform-specific debugging in your Visual Studio solution.
The other projects serve the same purpose only accept CSharp replaced with UnityScript. These are only the JavaScript (UnityScript) versions of the projects, which will exist only if you use JavaScript in your Unity game and simply if you have your scripts in the folders that trigger these projects to exist created.
Now that you've seen what projects go created, I'll explore the folders that trigger these projects and show you what their purposes are. Every folder path assumes information technology'due south underneath the /Assets root folder in your project view. Avails is always the root folder and contains all of your asset files underneath information technology. For instance, Standard Assets is actually /Assets/Standard Avails. The build process for your scripts runs through four phases to generate assemblies. Objects compiled in Phase 1 can't see those in Phase 2 considering they haven't nevertheless been compiled. This is important to know when you're mixing UnityScript and C# in the aforementioned projection. If you want to reference a C# grade from UnityScript, you need to make sure it compiles in an earlier stage.
Stage 1 consists of runtime scripts in the Standard Avails, Pro Standard Assets and Plug-ins folders, all located nether/Assets. This phase creates the Associates-CSharp-firstpass.csproj project.
Phase 2 scripts are in the Standard Assets/Editor, Pro Standard Assets/Editor and Plug-ins/Editor folders. The last folder is meant for scripts that interact with the Unity Editor API for pattern-fourth dimension functionality (think of a Visual Studio plug-in and how it enhances the GUI, but this runs in the Unity Editor). This phase creates the Assembly-CSharp-Editor-firstpass.csproj projection.
Phase 3 comprises all other scripts that aren't inside an Editor folder. This stage creates the Associates-CSharp-Editor.csproj project.
Phase 4 consists of all remaining scripts (those inside any other folder called Editor, such equally /Avails/Editor or /Assets/Foo/Editor). This stage creates the Assembly-CSharp.csproj project.
There are a couple other less-used folders that aren't covered here, such equally Resource. And at that place is the pending question of what the compiler is using. Is information technology .NET? Is information technology Mono? Is it .NET for the Windows Runtime (WinRT)? Is information technology .Net for Windows Phone Runtime? Figure 12 lists the defaults used for compilation. This is important to know, especially for WinRT-based applications considering the APIs available per platform vary.
Figure 12 Compilation Variations
Platform | Game Assemblies Generated Past | Last Compilation Performed Past |
Windows Phone 8 | Mono | Visual Studio/.Net |
Windows Store | .NET | Visual Studio/.NET (WinRT) |
Windows Standalone (.exe) | Mono | Unity - generates .exe + libs |
Windows Phone 8.1 | .Net | Visual Studio/.Internet (WinRT) |
When you perform a build for Windows, Unity is responsible for making 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 Telephone viii, it volition export a Visual Studio solution, except for Windows standalone, in which Unity generates the .exe and required .dll files. I'll discuss the various build types in the final article in the serial, when I embrace building for the platform. The graphics rendering at a low level is performed on the Windows platforms by DirectX.
Designing a game in Unity is a fairly straightforward procedure:
- Bring in your assets (artwork, audio and so on). Use the asset store. Write your ain. Hire an creative person. Note that Unity does take native support for Maya, Cheetah3d, Blender and 3dsMax, in some cases requiring that software be installed to piece of work with those native 3D formats, and it works with .obj and .fbx common file formats, as well.
- Write code in C#, JavaScript/UnityScript, or Boo, to command your objects, scenes, and implement game logic.
- Examination in Unity. Export to a platform.
- Examination on that platform. Deploy.
But Expect, I Want More!
This article serves as an overview of the compages and procedure in Unity. I covered the interface, basics of assigning code, GameObjects, components, Mono and .NET, plus more. This sets usa upwardly nicely for the adjacent article where I'll dive right into assembling game components for a 2D game. Keep an eye on Microsoft Virtual University, as I'll be doing a two-24-hour interval Unity learning event belatedly summer. And watch for local regional learning events at unity3d.com/pages/windows/events.
Adam Tuliperis a senior technical evangelist with Microsoft living in sunny Southern California. He's an indie game dev, co-admin of the Orangish Canton Unity Meetup, and a pluralsight.com writer. He and his wife are virtually to have their 3rd child, so reach out to him while he still has a spare moment at adamt@microsoft.com or on Twitter at twitter.com/AdamTuliper.
Cheers to the following technical experts for reviewing this commodity: Matt Newman (Subscience Studios), Jaime Rodriguez (Microsoft) and Tautvydas Žilys (Unity)
Source: https://docs.microsoft.com/en-us/archive/msdn-magazine/2014/august/unity-developing-your-first-game-with-unity-and-csharp
0 Response to "Detect When Application Gets Focus Again Unity"
Publicar un comentario