Unity Programming Game
Unity Programming Game
com/
Published February 2014
share:
This manual is the intellectual property of MakeUseOf. It must only be published in its original form. Using parts or republishing altered parts of this guide is prohibited without permission from MakeUseOf.com
Think youve got what it takes to write a manual for MakeUseOf.com? Were always willing to hear a pitch! Send your ideas to [email protected].
Table Of Contents
1.Introduction 2.Versions of Unity 2.1Pricing 2.2Features 3.Installing Unity 4 4 4 4 5 5 8 8 8 8 9 9 9 10 16 16 17 17 17 18 18 18 19 20 21 22 23
4.Introduction to the Object-Oriented Paradigm 5.Unity Basics 5.1Unity Entities 5.1.1Meshes 5.1.2GUI Elements 5.1.3Materials 5.1.5Lights 5.1.6Particle Systems 6.Example: Basic Elements of a Game 7.Scripting in Unity 7.1Transform 7.2Renderer 7.3Physics 7.4Collision 7.5Time Correction 7.6Audio Sources and Listeners 7.7Input 7.8Debugging a Script 8.Example: Scripting Pong 9.Exploring Documentation / Learning More 10.Building Your Game / Compiling 11.Closing Notes
3
share:
1.Introduction
A surprising feature of the Internet economy is the rise of indie videogames. Once the exclusive domain of thousandman, multi-million dollar triple-A studios, a number of toolsets have been developed that bring modern game development resources into the hands of individuals or small, ad-hoc collections of programmers and designers. These indie game development teams have demonstrated an agility and risk-tolerance that, in many cases, allows them to push gameplay innovation faster than their big budget counterparts. A number of shockingly successful indie titles have premiered in recent years, includingMinecraft,Limbo, andSuper Meat Boy. In the rapidly evolving landscape of indie game development,Unityhas emerged as something of a de-facto standard: its low cost, ease of use, and broad feature set make it ideal forrapid game development. Even large studios such as CCP (Developers ofEve Online) use it for rapidly prototyping game concepts. Unity provides a game engine in a box - a physics and rendering engine with hooks for several scripting languages, adaptable to virtually any genre of videogame. While Unity does provide a visual editor for manipulating the game environment, Unity is not a zero programminggame creator tool. Unity requires the ability to program to produce results, but also gives you a much more flexible and powerful tool than any game maker program possibly could. Unity wont do the work for you, but it does serve to lower the barrier to entry substantially. Starting completely from scratch with C++ and OpenGL, it can take days to get to the point where theres actually something rendered onscreen. Using Unity, it takes about ten seconds. Unity puts the basic elements of game creation into the hands of novice programmers in a fast, intuitive way.
2.Versions of Unity
Unity comes in two basic flavors: the pro version and the free version. There are a number of differences (you can see the full listhere), but, broadly speaking, the pro version supports a number of visual improvements (like real-time soft shadows and post-processing), and a large number of relatively minor features that are extremely helpful for more complex games. That said, for most relatively simple games you might want to build, the free version of Unity is perfectly adequate. Well break down the key differences below in more detail for those interested.
2.1Pricing
The free version of Unity is, of course, free. However, there are a few limitations: the free version of Unity cannot be licensed to any company with an annual income of more than $100,000. While such organizations are beyond the scope of this guide, if you suspect you might become such an organization, its probably wise to spring for the Pro version. The Pro version of Unity is $75 a month, or $1500 for a permanent license, and has no limits on what you can do with the games created with it. There is also a 30-day free trial available, which well be using for this guide, in order to give you as complete an overview of the available features as possible. A one-year student license is also available through Studica for $129.
2.2Features
There are many features absent in the free version of Unity. However, the most important differences are as follows: the free version of Unity lacks a number of rendering options that allow for better-looking, faster-running games (LOD support, screen-space post-processing, advanced shaders, real-time soft shadows, and deferred rendering). It also lacks the full mechanim animation system, and some AI tools. In general, for complex, large-scale projects, or projects where graphical performance is important, the pro version is worthwhile. I use the pro version, because I develop virtual reality games for theOculus Rift, and the screen-space post-processing support is necessary to correctly interact with the headset. You can check out an early alpha build of one of my VR games,BeatRunner. It should give you a sense for what Unity makes possible.
4
share:
3.Installing Unity
Unity is straightforward to install. You can download the executable here (for the OSX installer, click the link that says developing onMac OSX?). Let it download, run it, and follow the installer instructions. When the installation is finished, a window entitled activate your Unity license will appear. Check the box marked activate a free 30-day trial of Unity Pro and click OK. Congratulations! You know have a 30-day trial of Unity Pro. When the trial expires, if you dont want to buy the pro version, you can switch to the free version and keep your existing content.
5
share:
Go to new script, enter the name you want, and click create and add.
Now you have a new script, that you can edit by double-clicking on it! A class file looks something like this: HTTP://MAKEUSEOF.COM ANDRE INFANTE, HTTP://WWW.PETAFL0P.COM 6
share:
Along with Start and Update, you can instantiate your own methods with almost any name. However, methods that you create wont run unless theyre called. Lets declare a method for a hypothetical class called myClass that adds two numbers together. public float addTwoNumbers(float a, float b){ return a+b; } This declares a public (accessible to other objects) method that returns a float, called addTwoNumbers, which takes two floats as input (called a and b). It then returns the sum of the two values as its output. Calling this method from within the same class (say, from inside Update) looks like this: float result = addTwoNumbers(1,2); Calling the method from another class is similar: myClass instance; float result = instance.addTwoNumbers(1, 2); Again, this just creates an instance of our class, accesses the appropriate method and feeds it the numbers we want to add, then stores the result in result. Simple. If your script is attached to an object that has special properties (like a particle emitter) that cant be accessed under the normal set of GameObject parameters, you can choose to treat it as a different kind of game entity by using the GetComponent method. The syntax for that looks like this: GetComponent<ParticleSystem>().Play(); If any of this is unfamiliar to you, go back and go through the C# primer. Itll save you a lot of frustration as we proceed.
7
share:
5.Unity Basics
In this section, were going to work our way through the basic mechanics of the Unity engine. The workflow in Unity goes something like this: create an entity to serve a role in the game (blank GameObjects can be used for abstract logical tasks). Then, either write or find a class file, and add it to the entity as a script (using the add component button in the inspector view. Then run, test, debug, repeat until it works and move on to the next element of the game. Unitycomes with a number of basic view tabs that can be laid out in various ways to the taste of the user. The big five are the game tab, the scene tab, the inspector tab, the project tab, and the hierarchy tab. The game tab, when the play button is depressed, displays a running instance of the game that the user can interact with and test. The scene tab provides a static, editable version of the gameworld. The inspector tab allows the user to modify individual entities in the game world by selecting them in the editor tab. The project tab allows the user to browse through the projects files and drag models, materials, and other resources into the editor tab to place them in the gameworld. Finally, the hierarchy tab shows all objects in the world, allowing you to find distant objects in the scene, and parent entities to one another by clicking and dragging. See the diagram below for the locations of all these things.
5.1Unity Entities
5.1.1Meshes
Meshes are the way 3D geometry is represented in Unity. The user can either use Unitys built-in primitive objects (cubes, spheres, cylinders, etc), or importtheir own 3D modelsfrom a modelling package like Blender or Maya. Unity supports a variety of 3D formats, including Collada (.fbx), and .3ds. The basic tools for manipulating meshes are the scaling, rotation, and translation buttons in the upper left corner of the interface. These buttons add control icons to the models in the editor view, which can then be used to manipulate them in space. To alter the texture or physics properties of an object, select them and use the inspector view to analyze the material and rigidbody elements.
5.1.2GUI Elements
Traditional GUI sprites and text can be displayed using the GUI Text and the GUI Texture GameObjects in the editor. HTTP://MAKEUSEOF.COM ANDRE INFANTE, HTTP://WWW.PETAFL0P.COM 8
share:
5.1.3Materials
Materials are combinations of textures andshaders, and can be dragged directly onto game objects from the project tab. A large number of shaders come with Unity Pro, and you can adjust the texture attached to them using the inspector tab for an object that theyre applied to. To import a texture, just convert it to a jpg, png, or bmp, and drag it into the assets folder under the Unity project directory (which appears in My Documents by default). After a few seconds, a loading bar will appear in the editor. When it finishes, youll be able to find the image as a texture under the project tab.
5.1.5Lights
Lights are GameObjects which project radiance onto the world. If there are no lights in your scene, all polygons are drawn at the same brightness level, giving the world a flat look. Lights can be positioned, rotated, and have several internal characteristics that you can customize. The intensity slider controls the brightness of the light, and the range controls how quickly it fades out. The guidelines in the scene view show you the maximum range of the illumination. Play with both settings to achieve the desired effect. You can also adjust the color of the light, the pattern (cookie displayed on the surface the light is pointed at, and what kind of flare appears onscreen when looking directly at the light. The cookie can be used to fake more realistic light patterns, create dramatic false shadows, and simulate projectors. The three main kinds of light are spot, point, and directional. Spot lights have a location in 3D space and project light only in one direction in a cone of variable angle. These are good for flashlights, searchlights, and, in general, give you more precise control of lighting. Spot lights can cast shadows. Point lights have a location in 3D space, and cast light evenly in all directions. Point lights do not cast shadows. Directional lights, finally, are used to simulate sunlight: they project light in a direction as though from infinitely far away. Directional lights affect every object in the scene, and can produce shadows.
5.1.6Particle Systems
Particle systems are the term for Unity GameObjects that generate and control hundreds or thousands of particles simultaneously. Particles are small, optimized 2D objects displayed in 3D space. Particle systems use simplified rendering and physics, but can display thousands of entities in real time without stuttering, making them ideal for smoke, fire, rain, sparks, magic effects, and more. There are a lot of parameters that you can tweak to achieve these effects, and you can access them by spawning a particle system under the component editor, selecting the particle system, and then opening the inspector tab. You can change the size, speed, direction, rotation, color, and texture of each particle, and set most of those parameters to change over time as well. Under the collision attribute, if you enable it and set the simulation space to world youll get particles that will collide with objects in the world, which can be used for a number of realistic particle effects, including rain, moving water, and sparks.
9
share:
10
share:
Scale it appropriately, duplicate it, and put a sphere between the paddles for the ball.
Then, create a 3DText object and scale and position it correctly, changing the font size attribute to get a less pixelated image.
11
share:
Next, create two particle systems, pick the characteristics you want, and attach them to the paddles.
12
share:
Next, youll want to position and rotate the camera so that it frames the scene correctly. While the camera is selected, you can see a small preview of the cameras view in the lower right hand corner.
Before we finish, we need to create two additional cubes to be bumpers, to prevent the ball from bouncing out of the game area. We can make them invisible by unchecking the mesh renderer in the inspector tab.
13
share:
If you hit play, you can now see the basic elements of our game laid out. They wont do anything yet, but well get to that!
14
share:
Now that weve got that setup, were going to talk about whats involved in scripting these elements to make a game.
15
share:
7.Scripting in Unity
Once you have a script attached to an object, you can revise it by double clicking on it in the inspector. This opens MonoDevelop, the default development environment for Unity. In essence, Monodevelop is a text editor with features specifically optimized towardprogramming. Keywords and comments are highlighted in blue and green, and numerical values and strings appear in red. If youve used Eclipse or other IDEs, MonoDevelop is very similar. You can build your scripts from inside the editor, to check for syntax errors, like so:
In general, to get your script to interact with Unity, youll need to reference elements that the object holding the script possesses (you can see a list of these elements under the inspector tab when the relevant object is selected). You can then call methods or set variables for each of these elements to enact the changes you want. If you want a script on an object to affect the properties of a different object, you can create an empty GameObject variable in your script, and use the inspector to assign it to another object in the scene. The screenshots below show what that looks like. A list of the elements an object might have is as follows (taken from the inspector view of one of our paddles in the above example): Transform Cube (Mesh Filter) Box Collider Mesh Renderer
Each of these aspects of the object can be influenced from within a script. Next, well look at exactly how.
7.1Transform
The transform functions for a GameObject in Unity control the physical parameters of that object: its scale, its position, and its orientation. You can access them from within a script like this: HTTP://MAKEUSEOF.COM ANDRE INFANTE, HTTP://WWW.PETAFL0P.COM 16
share:
7.2Renderer
The renderer functions in Unity allow you to control the way the surfaces of props are rendered on-screen. You can reassign the texture, change the color, and change the shader and visibility of the object. The syntax looks like this: renderer.enabled = false; renderer.material.color = new Color(0, 255, 0); mainTexture = myTexture; renderer.material.shader = newShader; renderer.material.
Most of these have pretty clear functions. The first example makes the object in question invisible: a useful trick in a number of situations. The second example assigns a new RGB color (namely, green) to the object in question. The third assigns the main diffuse texture to a new Texture variable. The last example changes the shader of the objects material to a newly defined shader variable.
7.3Physics
Unity comes with an integratedphysics enginethat allows you to assign the physical properties of objects and let the details of their simulation be handled for you. In general, rather than trying to implement your own physics using a textbook and the transform system, it is simpler and more robust to use Unitys physics engine to the greatest extent possible. All physics props require colliders. However, the actual simulation itself is handled by a rigidbody, which can be added in the inspector view. Rigidbodies can be kinematic or nonkinematic. Kinematic physics props collide with (and effect) nonkinematic physics props around them, but are unaffected by collision themselves. Static kinematic props are the proverbial immoveable objects, and moving kinematic objects are the proverbial unstoppable force (for the record, when they collide, they simply pass through each other). Beyond that, you can adjust the angular drag of the object (how much energy it takes to spin it), change its mass, dictate whether or not its affected by gravity, and apply forces to it. Examples: rigidbody.angularDrag = 0.1f; rigidbody.mass = 100; rigidbody.isKinematic = false; rigidbody. useGravity = true; rigidbody.AddForce(transform.forward * 100); These are all pretty self-explanatory. The only thing to note here is the use of transform.forward. Vector3s all have three components(.forward, .up, and .right) associated with them, which can be accessed and rotates with them (forward is the direction of the blue arrow in the editor). transform.forward is simply the forward vector for the current object with magnitude 1. It can be multiplied by a float to create more force on the object. You can also reference transform.up and transform.right, and negate them to get their reverses.
7.4Collision
Often, when building a game, youd like a collision to result in some change-of-state in your code, beyond just physics simulation. For this, youll need a collision detection method.
17
share:
7.5Time Correction
One important factor to keep in mind when youre manipulating objects in this way has to do with framerate. No matter how carefully you optimize, framerates will always vary, and you dont want your game speed to vary accordingly. If someone else runs your game on a faster computer than you developed it on, you dont want the game to run at double speed. The way you correct for this is by multiplying the values youre using by the time it took to render the last frame. This is done by using Time.deltaTime. This effectively changes the speed of any variable youre incrementing every frame from change per frame to change per second, and you should probably make this change to any value youre incrementing or decrementing every frame.
Now that weve covered how to create, render, and control objects, lets talk about the other sense that computer games can serve: namely, sound. Unity supports two kinds of sounds: 2D and 3D sounds. 3D sounds vary their volume based on distance, and distort as they move relative to the camera; 2D sounds do not. 2D sounds are appropriate for voice-overs and background music, and 3D sounds apply to sounds generated by events in the world. In order to change whether or not a sound is 3D, select it in the project view, switch to the inspector view and select the appropriate option from the dropdown menu, then press the reimport button. In order to actually play the sound, youll need to attach an audiosource to a prop (the prop you want the sound to originate from, in the case of a 3D sound. Then youll need to open the audioclip field and select your sound file. You can use myAudioSource.Pause() and myAudioSource.Play() to control those sound files. You can adjust the falloff behaviors, volume, and doppler shifting of the sounds under the inspector tab for the audiosource.
7.7Input
A game that doesnt take any input from the user isnt much of a game. There are a lot of different kinds of input you can read in, and almost all of them are accessible through the Input and KeyCode objects. Some sample input stateHTTP://MAKEUSEOF.COM ANDRE INFANTE, HTTP://WWW.PETAFL0P.COM 18
share:
7.8Debugging a Script
Lets say a script doesnt work. As the good doctor says, bangups and hangups can happen to you. If there are outright syntax errors with your C#, the game will generally refuse to run when you hit play, and some fairly useful error messages are provided if you build the scripts from within the editor. See below:
These bugs are typically not the most difficult to fix. What can be more problematic are subtle semantic errors, in which you have successfully written a file full of valid C# just not one that does what you thought it would. If you have one of these errors, and youre having trouble tracking it down, there are a few things you can try to improve the situation. The first is to pause the execution of the game, and check the console. You can pause the game by clicking on the pause icon in the upper middle portion of the editor, and then selecting console from the bottom of the window menu (or pressing Ctrl-Shift-C). Even if there are no errors, warnings can still help to give some clues as to what might be going wrong. If this doesnt work, you can also try to get some idea about the state of your script by printing the state of internal variables to validate that the program is doing what you think its doing. You can use Debug.Log(String); to print the contents of a string to the console when the program execution hits that line. In general, if you work backwards from what you think should be happening through the things that should be making it happen, eventually you will reach a point where your debug prints dont do what you expect them to do. Thats where your error is.
19
share:
You candownload my Pong demo, if youd like to see everything Ive outlined in action. It runs on Windows, Mac and Linux systems. HTTP://MAKEUSEOF.COM ANDRE INFANTE, HTTP://WWW.PETAFL0P.COM 20
share:
21
share:
The process from there is self explanatory: select your options, and hit build; the game will prompt you for a directory to install to, and will place both the executable and data directory there. These two files can be zipped together and distributed (just make sure you arent charging for a game built in the Unity demo, as this violates the terms of service).
22
share:
11.Closing Notes
As with any game development tool, the key to success with Unity is iterative development. You have to build in manageable increments - be ambitious, by all means, but be ambitious in small chunks, and arrange those chunks such that, even if you fall short of your ultimate ambition, youll at least wind up with a coherent product. Get the most crucial elements in first: have an idea in mind of your minimum viable product, the simplest, most bare-bones thing you could possibly create and still feel as though you achieved something worthwhile. Get to that minimum viable project before moving on to larger ambitions. This tutorial gives you a strong starting place, but the best way to learn Unity is while building a game. Start building a game, fill gaps in your knowledge as they come up, and the gradual flow of knowledge will erode away the things you dont know surprisingly quickly. Unity is a powerful tool, and with a bit of exploration, you can be building impressive projects with it quicker than you might expect. Good luck, and enjoy Unity!
Guide Published: February 2014
23
share:
Did you like this PDF Guide? Then why not visit MakeUseOf.com for daily posts on cool websites, free software and internet tips?
If you want more great guides like this, why not subscribe to MakeUseOf and receive instant access to 50+ PDF Guides like this one covering wide range of topics. Moreover, you will be able to download free Cheat Sheets, Free Giveaways and other cool things.
Follow MakeUseOf:
Think youve got what it takes to write a manual for MakeUseOf.com? Were always willing to hear a pitch! Send your ideas to [email protected].