<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>3D Game Engine Programming</title>
	<atom:link href="http://3dgep.com/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://3dgep.com</link>
	<description>Helping you build your dream game engine.</description>
	<lastBuildDate>Wed, 22 May 2013 09:07:53 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Networking in Unity</title>
		<link>http://3dgep.com/?p=4609</link>
		<comments>http://3dgep.com/?p=4609#comments</comments>
		<pubDate>Mon, 17 Dec 2012 21:47:08 +0000</pubDate>
		<dc:creator>Marc Bastiaansen</dc:creator>
				<category><![CDATA[Unity]]></category>
		<category><![CDATA[Client]]></category>
		<category><![CDATA[Network Instantiate]]></category>
		<category><![CDATA[Networking]]></category>
		<category><![CDATA[Player]]></category>
		<category><![CDATA[RPC]]></category>
		<category><![CDATA[Server]]></category>

		<guid isPermaLink="false">http://3dgep.com/?p=4609</guid>
		<description><![CDATA[In this article I will introduce the networking functionality included in Unity 3.5. I will build a simple authorative server solution, introduce the NetworkView component, and show you how RPCs can be used. <a href="http://3dgep.com/?p=4609">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="attachment_4565" class="wp-caption alignleft" style="width: 160px"><a href="http://3dgep.com/wp-content/uploads/2012/12/UnityNetworkingThumb.png"><img class="size-thumbnail wp-image-4565" src="http://3dgep.com/wp-content/uploads/2012/12/UnityNetworkingThumb.png" alt="Unity Particles" width="150" height="150" /></a><p class="wp-caption-text">Unity Networking</p></div>
<p>In this article I will introduce the networking functionality included in Unity. I will build a simple authorative server solution, introduce the NetworkView component, and show you how RPCs can be used. The screenshots are from Unity 3.5, but the solution works for Unity 4.0 as well.</p>
<p><span id="more-4609"></span></p>
<div style="clear: both"><div class='toc wptoc'>
<h2>Table of Contents</h2>
<ol class='toc-odd level-1'>
	<li>
		<a href="#Introduction">Introduction</a>
	</li>
	<li>
		<a href="#A_brief_history_of_networking">A brief history of networking</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Peer_to_Peer_Lockstep">Peer to Peer Lockstep</a>
			</li>
			<li>
				<a href="#Authorative_ServerDumb_client">Authorative Server/Dumb client</a>
			</li>
			<li>
				<a href="#Client_Side_Prediction">Client Side Prediction</a>
			</li>
			<li>
				<a href="#Lag_Compensation">Lag Compensation</a>
			</li>
			<li>
				<a href="#Non_authorative_server">Non authorative server</a>
			</li>
		</ol>
	<li>
		<a href="#A_Unity_server">A Unity server</a>
	</li>
	<li>
		<a href="#Client_and_server_projects">Client and server projects</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Project_wizard">Project wizard</a>
			</li>
			<li>
				<a href="#Run_in_background">Run in background</a>
			</li>
		</ol>
	<li>
		<a href="#A_Unity_client">A Unity client</a>
	</li>
	<li>
		<a href="#Your_First_Networking_Solution">Your First Networking Solution</a>
	</li>
	<li>
		<a href="#Network_View">Network View</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Observed">Observed</a>
			</li>
			<li>
				<a href="#State_Synchronization">State Synchronization</a>
			</li>
		</ol>
	<li>
		<a href="#Network_Instantiate">Network Instantiate</a>
	</li>
	<li>
		<a href="#Authorative_Server">Authorative Server</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Server_Project">Server Project</a>
				<ol class='toc-odd level-3'>
					<li>
						<a href="#Shared_Unity_package">Shared Unity package</a>
					</li>
					<li>
						<a href="#Spawn_players">Spawn players</a>
					</li>
				</ol>
			<li>
				<a href="#Client_Project">Client Project</a>
			</li>
			<li>
				<a href="#Second_Networking_Solution">Second Networking Solution</a>
			</li>
			<li>
				<a href="#Spawning_madness">Spawning madness</a>
			</li>
		</ol>
	<li>
		<a href="#RPCs">RPCs</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Buffered_RPCs">Buffered RPCs</a>
			</li>
			<li>
				<a href="#Restrictions_on_RPCs">Restrictions on RPCs</a>
			</li>
		</ol>
	<li>
		<a href="#Improved_Spawning">Improved Spawning</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Clean_up_client_side">Clean up client side</a>
			</li>
			<li>
				<a href="#Clean_up_server_side">Clean up server side</a>
			</li>
			<li>
				<a href="#Run_the_solution">Run the solution</a>
			</li>
		</ol>
	<li>
		<a href="#Movement">Movement</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Server_project">Server project</a>
			</li>
			<li>
				<a href="#Client_project">Client project</a>
			</li>
			<li>
				<a href="#Final_run">Final run</a>
			</li>
		</ol>
	<li>
		<a href="#Download">Download</a>
	</li>
</ol>
</div>
<div class='wptoc-end'>&nbsp;</div></div>
<span id="Introduction"><h1>Introduction</h1></span>
<p>If you are planning to make a multiplayer game in Unity, be it two player turn based or massive multiplayer online, you will have to implement some sort of networking solution capable of ensuring that all players share the same consistent world view. This will require the handling of problems such as:</p>
<ul>
<li>players playing on differing hardware platforms (cpu/memory), such as pcs and mobiles</li>
<li>players with differing connection speeds</li>
<li>differing network latency between players (round trip time), and differences in the variation thereof (jitter)</li>
<li>lossy connections and the handling of lost data</li>
</ul>
<p>For real time games the above problems are especially relevant and if not handled correctly will result in players experiencing &#8220;lag&#8221;.</p>
<span id="A_brief_history_of_networking"><h1>A brief history of networking</h1></span>
<p>Before diving into the networking solution that Unity offers, lets briefly look at the history of multiplayer games and their networking solutions.</p>
<ul>
<li>
<span id="Peer_to_Peer_Lockstep"><h2>Peer to Peer Lockstep</h2></span>
<div id="attachment_4631" class="wp-caption alignleft" style="width: 112px"><a href="http://3dgep.com/wp-content/uploads/2012/11/fullyStar.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/fullyStar.png" alt="Fully connected star topology" title="Fully connected start topology" width="102" height="92" class="size-full wp-image-4631" /></a><p class="wp-caption-text">Fully connected star topology</p></div>
<p>Initially, each computer exchanged game information with each of the other computers in a star topology. The game consisted of &#8220;turns&#8221; and in each turn a computer could choose from a limited number of &#8220;moves&#8221;. Once all the computers had communicated their next move to all the other computers, each computer carried out the moves after which it was time for the next turn. Assuming that all computers started from the same initial game state, this would ensure that all games played out identically across computers. The disadvantage of this networking solution is that each computer has to wait until it has received the move from the last computer, the slowest computer thus determing the pace of the turns (and thus lag). Real Time Strategy games typically use variants of peer to peer lockstep, albeit with better handling of the lag issues.</li>
<li>
<span id="Authorative_ServerDumb_client"><h2>Authorative Server/Dumb client</h2></span>
<div id="attachment_4632" class="wp-caption alignleft" style="width: 120px"><a href="http://3dgep.com/wp-content/uploads/2012/11/serverClient.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/serverClient.png" alt="Star topology for client-server" title="Star topology for client-server" width="110" height="97" class="size-full wp-image-4632" /></a><p class="wp-caption-text">Star topology for client-server</p></div>
<p>To avoid having to wait on the slowest computer, each computer now communicates with a single server. The server has the game &#8220;world&#8221; and the clients just receive a view on this world. The clients have (almost) no code, they are just dumb terminals sending input (key presses) to the server. The server then carries out the input and sends back a &#8220;picture&#8221; of the resulting world. There is no longer a problem of keeping the game world consistent across computers as there is only one world (on the server). The solution works fine for computers with the same low network latency but begins to fall apart when players have higher, differing latency. For players with a high latency, the game quickly become unplayable, the world moving in jarring jumps. Doom worked like this and if you had a high latency then most chances were you were dead before you had a chance to see what hit you.</li>
<li>
<span id="Client_Side_Prediction"><h2>Client Side Prediction</h2></span>
<p>To smoothen the game experience, clients no longer wait until they receive a view back from the server. They take the players input and predict what will happen, immediately updating the world view accordingly. This requires the client to know about the game mechanics and game objects, thus the client is no longer dumb. The resulting game play is much more responsive. Of course, a problem occurs when the server world view comes back and differs from what the client predicted. The world view is then yanked back in line with the server view, often causing a noticeable glitch. This solution was first introduced in Quakeworld.</li>
<li>
<span id="Lag_Compensation"><h2>Lag Compensation</h2></span>
<div id="attachment_4641" class="wp-caption aligncenter" style="width: 700px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Lag_compensation.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/11/Lag_compensation.jpg" alt="Client side prediction and lag compensation" title="Client side prediction and lag compensation" width="690" height="372" class="size-full wp-image-4641" /></a><p class="wp-caption-text">Client side prediction and lag compensation</p></div>
<p>Reverting to the server state when a client prediction is off, actually means that the world view of the client jumps back in time. To understand this, say that it took 200 ms for the client input to reach the server, and another 200 ms for the resulting world view to come back from the server. The client has in the mean time moved forward 400 ms in time using it&#8217;s own predictions. If the client has to revert to the server view resulting from it&#8217;s input 400ms ago, it is thus jumping back in time to the time of that input. To avoid this, the client would have to first rewind time and then repredict forward in time to reach the current time again. If the game play mechanics are reasonably deterministic then corrections will occur rarely as server and client are calculating the same world view. Input from other players is basically the only cause for correction, such as the firing of a rocket point blank at the back of the head. This solution results in smooth, responsive gameplay and was first introduced in CounterStrike.</li>
<li>
<span id="Non_authorative_server"><h2>Non authorative server</h2></span>
<p>As a side note, clients can be authorative in that they are allowed to process the players inputs and update the world themselves. In this case, the server does not own the world, it just serves to update the world according to views from it&#8217;s clients and distribute these views to the other players. While this ensures that game play is responsive, it can lead to clients having different conflicting world states requiring solutions to resolve these conflicts. It also introduces the risk of cheating clients, one player claiming to have shot another when he didn&#8217;t even have a gun, for example. This networking solutions is seldom (if ever) used for games. Sometimes a peer to peer solution, with one of the clients being both server and client, is called a non authorative server, but typically the client-server is authorative.</li>
</ul>
<p>Reference: <a href="http://gafferongames.com/networking-for-game-programmers/what-every-programmer-needs-to-know-about-game-networking/" title="What every programmer needs to know about game networking" target="_blank">What every programmer needs to know about game networking</a></p>
<span id="A_Unity_server"><h1>A Unity server</h1></span>
<p>To understand the networking solution that comes with Unity, let&#8217;s start by building a server. Create a new, empty Unity project and add a script called ServerMain.js with the following code:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="ServerMain.js">
var listenPort = 25000;
var maxClients = 5;

function startServer() {
	Network.InitializeServer(maxClients, listenPort, false);	
}

function stopServer() {
	Network.Disconnect();
}
</pre>
</div>
<p>The <a href="http://docs.unity3d.com/Documentation/ScriptReference/Network.html" target="_blank">Network</a> class is the main networking class in Unity. The function <strong>InitializeServer()</strong> starts up the server, taking the maximum number of clients allowed:</p>
<pre>
var maxClients = 5;
</pre>
<p>as well as the port to listen to for incoming clients:</p>
<pre>
var listenPort = 25000;
</pre>
<p>The last parameter to the <strong>Network.InitializeServer()</strong> function  (<strong>false</strong> in the code above) indicates whether or not the server should use <strong>NAT punchthrough</strong> to enable clients to connect with it. See the <a href="http://docs.unity3d.com/Documentation/Components/net-HighLevelOverview.html" target="_blank">Network Overview</a> for more details. For now, leave this at false. </p>
<p>The function <strong>Network.Disconnect()</strong> stops the server.</p>
<p>To complete the server side script, add the following UI code to the same script file:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="ServerMain.js">
function OnGUI ()
{
 	if (Network.peerType == NetworkPeerType.Disconnected) {
        GUILayout.Label("Network server is not running.");
        if (GUILayout.Button ("Start Server"))
		{				
			startServer();	
		}
    }
    else {
    	if (Network.peerType == NetworkPeerType.Connecting)
        	GUILayout.Label("Network server is starting up...");
    	else { 
        	GUILayout.Label("Network server is running.");        	
        	showServerInformation(); 	
        	showClientInformation();
        }
        if (GUILayout.Button ("Stop Server"))
		{				
			stopServer();	
		}
    }
}

function showClientInformation() {
	GUILayout.Label("Clients: " + Network.connections.Length + "/" + maxClients);
    	for(var p: NetworkPlayer in Network.connections) {
		GUILayout.Label(" Player from ip/port: " + p.ipAddress + "/" + p.port);	
	}
}

function showServerInformation() {
	GUILayout.Label("IP: " + Network.player.ipAddress + " Port: " + Network.player.port);  
}
</pre>
</div>
<p>This code snippet uses the <strong>startServer()</strong> and <strong>stopServer()</strong> functions we defined above and adds some buttons to start/stop the server. It uses the <strong>Network.peerType</strong> property to determine the status of the connection and shows this on the screen. The value of the peerType can be:</p>
<ul>
<li><strong>Disconnected</strong> : No client connection running. Server not initialized</li>
<li><strong>Server</strong> : Running as server</li>
<li><strong>Client</strong> : Running as client</li>
<li><strong>Connecting</strong> : Attempting to connect to a server</li>
</ul>
<p>The code also uses </p>
<pre>
for(var p: NetworkPlayer in Network.connections)
</pre>
<p>A <a href="http://docs.unity3d.com/Documentation/ScriptReference/NetworkPlayer.html" title="Unity NetworkPlayer" target="_blank">NetworkPlayer</a> is a datastructure containing information about a client (such as the ip address and port). Network.connections returns a list of all connected NetworkPlayers. </p>
<p>To finish the server side, create an empty <strong>GameObject</strong> and add the <strong>ServerMain.js</strong> script to it. You should now be able to start and stop the server.</p>
<span id="Client_and_server_projects"><h1>Client and server projects</h1></span>
<p>Before we build the client side code, we first need to configure Unity to allow both the client and the server projects to run on the same pc. This is easy for development and debugging purposes.</p>
<ul>
<li>
<span id="Project_wizard"><h2>Project wizard</h2></span>
<p>Unity does not allow the same project to be opened more than once. It also automatically reopens the last project you edited. This combination means that if you have any project open in Unity, clicking on Unity again will result in an error message. This can be avoided by selecting <strong>Edit > Preferences</strong> from the main menu in the Unity editor and then check &#8220;<strong>Always Show Project Wizard</strong>&#8220;.</p>
<div id="attachment_4693" class="wp-caption alignnone" style="width: 526px"><a href="http://3dgep.com/wp-content/uploads/2012/11/ProjectWizard.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/ProjectWizard.png" alt="Unity - Preferences" title="Unity - Preferences" width="516" height="289" class="size-full wp-image-4693" /></a><p class="wp-caption-text">Unity &#8211; Preferences</p></div>
<p>Unity will now no longer automatically reopen the last project, but allow you to select the project yourself on start up. You should now be able to open both a server project and a client project.
</li>
<li>
<span id="Run_in_background"><h2>Run in background</h2></span>
<p>By default, Unity will only run the project when the game view is active (the mouse is in the view for example). If not active, the code is paused. This is a nuisance if you have a server and a client project open at the same time and are switching between them for development/debugging purposes. To get around this, select <strong>Edit > Project Settings > Player</strong> from the main menu in the Unity editor, and select <strong>Run In Background</strong> in the <strong>PlayerSettings</strong> inspector.</p>
<div id="attachment_4692" class="wp-caption alignnone" style="width: 470px"><a href="http://3dgep.com/wp-content/uploads/2012/11/RunInBakground.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/RunInBakground.png" alt="Unity - Player Settings" title="Unity - Player Settings" width="460" height="377" class="size-full wp-image-4692" /></a><p class="wp-caption-text">Unity &#8211; Player Settings</p></div>
<p>If you now run the server project, it will not stop running when the mouse leaves the game view screen. Remember to do this for both the client and the server projects.</p>
</li>
</ul>
<p>Note that as an alternative, bulding the server (.exe) and the client (.exe) projects and running the resulting executable also allows you to run both client and server at the same time on the same pc. </p>
<span id="A_Unity_client"><h1>A Unity client</h1></span>
<p>Now that we have a server, let&#8217;s build a client to connect to it. Create a new Unity project and add a script called ClientMain.js with following code:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="ClientMain.js">
var remoteIP = "127.0.0.1";
var remotePort = 25000;

function connectToServer() {
	Network.Connect(remoteIP, remotePort);	
}

function disconnectFromServer() {
	Network.Disconnect();
}
</pre>
</div>
<p>Again we use the <strong>Network</strong> class. The function <strong>Connect()</strong> tries to establish a connection to the server. The first parameter is the (remote) IP address of the server, which in the code above is set to:</p>
<pre>var remoteIP = "127.0.0.1"</pre>
<p>This is the default ip for <strong>localhost</strong> (the pc you are running on). This will work fine if the server is also running the same pc, but otherwise this should be set to the actual global ip address of the server. </p>
<p>The second parameter is the (remote) port of the server and should be identical to the <strong>listenPort</strong> in the ServerMain.js script.</p>
<p>The function <strong>Disconnect()</strong> is used to disconnect from the server. </p>
<p>To complete the client side script, add the following UI code to the same script file:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="ClientMain.js">
function OnGUI ()
{	
	if (Network.peerType == NetworkPeerType.Disconnected)
	{	
		GUILayout.Label("Not connected to server.");
		if (GUILayout.Button ("Connect to server"))
			connectToServer();					
	}
	else
	{
		if(Network.peerType == NetworkPeerType.Connecting)
			GUILayout.Label("Connecting to server...");
		else {
			GUILayout.Label("Connected to server.");
			GUILayout.Label("IP/port: " + Network.player.ipAddress + "/" + Network.player.port);
		}
		if (GUILayout.Button ("Disconnect"))
			disconnectFromServer();
	}
}
</pre>
</div>
<p>This code snippet uses the <strong>connectToServer()</strong> and <strong>disconnectFromServer()</strong> functions defined above. In addition, it adds some buttons to connect/disconnect to the server, and shows some status information using the <strong>Network.peerType</strong>.  To complete the client, create a new empty <strong>GameObject</strong> and add the <strong>ClientMain.js</strong> script to it.</p>
<span id="Your_First_Networking_Solution"><h1>Your First Networking Solution</h1></span>
<p>Run the Server project and press the &#8220;<strong>Start Server</strong>&#8221; button. Now run the Client project and press the &#8220;<strong>Connect to Server</strong>&#8221; button. </p>
<div id="attachment_4683" class="wp-caption aligncenter" style="width: 341px"><a href="http://3dgep.com/wp-content/uploads/2012/11/ServerClientConnected.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/ServerClientConnected.png" alt="Screenshot of client connected to server" title="Screenshot of client connected to server" width="331" height="334" class="size-full wp-image-4683" /></a><p class="wp-caption-text">Screenshot of client connected to server</p></div>
<p>If you are seeing something comparable to the above screenshot then congratulations, you have successfully built your first networking solution!</p>
<span id="Network_View"><h1>Network View</h1></span>
<p>The client server example above allows a connection to be established between server and client, but it doesn&#8217;t yet do anything useful. To improve, let&#8217;s first discuss the Unity <a href="http://docs.unity3d.com/Documentation/Components/class-NetworkView.html" target="_blank">Network View</a> component.</p>
<div id="attachment_4686" class="wp-caption aligncenter" style="width: 377px"><a href="http://3dgep.com/wp-content/uploads/2012/11/class-NetworkView.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/11/class-NetworkView.jpg" alt="Unity Network View" title="Unity Network View" width="367" height="221" class="size-full wp-image-4686" /></a><p class="wp-caption-text">Unity Network View</p></div>
<p>The Network View component can be added to any GameObject. It allows state information about the GameObject to be communicated across the network. It has the following key properties:</p>
<ul>
<li>
<span id="Observed"><h2>Observed</h2></span>
<p>This property determines the Component of the GameObject for which information will be sent over the network. This is a drop down allowing either a <b>Transform</b>, an <b>Animation</b>, a <b>RigidBody</b>, or a <b>script</b> to be selected. For the selected Component, all the state information required to &#8220;recreate&#8221; the state of the Component on a different client is sent across the network automatically (by default information is sent 15 times per second). Unity handles all of this information sending and recreating for you, thereby ensuring that all clients see the same state.
</li>
<li>
<span id="State_Synchronization"><h2>State Synchronization</h2></span>
<p>This property determines how information about the GameObject will be sent over the network. One option is <strong>Unreliable</strong> which means that <em>all</em> the state information about the Observed component will be sent every time (15 times per second). It is called unreliable because if the information is lost somewhere in the network (due to packets being dropped by a router for example) then it is not resent. For a real time racing game, such loss is quite acceptable as any resent information will be too late anyway. As long as the next packets contain the complete state again, the game can recover.</p>
<p>Another option is <strong>Reliable Delta Compressed</strong>. In this case, not the entire state information is sent every time but only the information that has changed since the last send (hence &#8220;delta&#8221;). It is called reliable because any information lost in the network is resent and is guaranteed to arrive at all clients. This is necessary because if any change packets are lost then the state on the remote client goes out of sync and any subsequent change packets are unusable. Sending only changes instead of the total state saves on bandwidth but the resending introduces delay, making it less suitable for real time games.
</li>
</ul>
<span id="Network_Instantiate"><h1>Network Instantiate</h1></span>
<p>Before showing how the Network View works in some sample code, there is another important function in the Network class to discuss. The <a href="http://docs.unity3d.com/Documentation/Components/net-NetworkInstantiate.html" target="_blank">Network.Instantiate()</a> function allows a prefab instance to be created on all connected clients (note the prefab must have a Network View). The syntax is:</p>
<pre>
static function Instantiate (prefab : Object, position : Vector3, rotation : Quaternion, group : int) : Object
</pre>
<p>Besides the prefab, the function also requires the position and rotation of the prefab. </p>
<p>The last parameter denotes the <em>Communication Group</em>. This allows clients to be split into different groups and the prefab would only be instantiated on clients in that group. This aovids having clients that are nowhere near each other in the game exchanging useless information. </p>
<p><strong>Instantiate()</strong> can be called by any client and/or the server, but whoever makes the call &#8220;owns&#8221; the instance. This means that if <strong>Instantiate()</strong> is called on a client, this client is authorative for that instance and can change the position and rotation etc. Other clients can cheat by modifying the position of the instance, but these chances are only local to that client and are not communicated across the network (and are overwritten by changes made by the owner). </p>
<p>We will be building an authorative server solution, so all calls to Instantiate need to be made on the server.</p>
<span id="Authorative_Server"><h1>Authorative Server</h1></span>
<p>To demonstrate the <strong>Network View</strong> and <strong>Network.Instantiate()</strong>, let&#8217;s extend our client-server solution so that a player gameobject is spawned every time a new client connects to the server.</p>
<span id="Server_Project"><h2>Server Project</h2></span>
<p>In the server project, create a folder called &#8220;<strong>Server</strong>&#8221; in the <strong>Project View</strong> and drag the script <strong>ServerMain.js</strong> into this folder. This folder will contain everything that is needed only on the server side. Also, delete the GameObject from the scene.</p>
<span id="Shared_Unity_package"><h3>Shared Unity package</h3></span>
<p>Create a second folder called &#8220;<strong>Game</strong>&#8220;. This folder will contain everything shared with the client project. Save the scene and call it &#8220;<strong>Game</strong>&#8220;. Drag the &#8220;<strong>Game.unity</strong>&#8221; scene into the &#8220;<strong>Game</strong>&#8221; folder. </p>
<p>Add a <strong>Plane</strong> GameObject to the scene with <strong>Position</strong> (0,0,0), <strong>Rotation</strong> (0,0,0), and <strong>Scale</strong> (1,1,1). Make sure the <strong>Main Camera</strong> shows the plane, for example <strong>Position</strong> (0,1,-10) and <strong>Rotation</strong> (0,0,0). Add a <strong>Directional light</strong> to the camera and set the <strong>Directional light</strong> to <strong>Position</strong> (0,0,0) and <strong>Rotation</strong> (0,0,0). </p>
<p>Add an empty GameObject called &#8220;<strong>GameController</strong>&#8221;  to the scene. Select the <strong>GameController</strong> and add a <strong>NetworkView</strong> component by selecting <strong>Component > Miscellaneous > Network View</strong> from the main menu. In the <strong>Inspector</strong>, set the <strong>State Synchronization</strong> property to &#8220;<strong>Off</strong>&#8220;, and the <strong>Observed</strong> property to &#8220;<strong>None</strong>&#8220;. This GameObject will serve as a global placeholder used to attach scripts. Why we need a <strong>NetworkView</strong> here that is doing &#8220;nothing&#8221;  will be explained later on.<br />
<div id="attachment_4875" class="wp-caption aligncenter" style="width: 327px"><a href="http://3dgep.com/wp-content/uploads/2012/11/DummyNetworkView.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/DummyNetworkView.png" alt="None/Off NetworkView" title="None/Off NetworkView" width="317" height="82" class="size-full wp-image-4875" /></a><p class="wp-caption-text">None/Off NetworkView</p></div></p>
<p>Your scene hierarchy should now look like:</p>
<div id="attachment_4847" class="wp-caption aligncenter" style="width: 297px"><a href="http://3dgep.com/wp-content/uploads/2012/11/GameHierarchy.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/GameHierarchy.png" alt="Scene hierarchy" title="Scene hierarchy" width="287" height="139" class="size-full wp-image-4847" /></a><p class="wp-caption-text">Scene hierarchy</p></div>
<p>Now we will create a simple cube prefab which will serve as our &#8220;player&#8221; object. To do this, add a <strong>Cube</strong> GameObject to the scene. Rename the cube to &#8220;<strong>Player</strong>&#8220;. Add a <strong>Rigidbody</strong> component and also a <strong>NetworkView</strong> component. In the <strong>Inspector</strong>, drag the <strong>Rigidbody</strong> component onto the &#8220;<strong>Observed</strong>&#8221; property of the <strong>NetworkView</strong> component. </p>
<div id="attachment_4844" class="wp-caption aligncenter" style="width: 362px"><a href="http://3dgep.com/wp-content/uploads/2012/11/NetworkViewRigidBody.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/NetworkViewRigidBody.png" alt="Networkview observe Rigidbody" title="Networkview observe Rigidbody" width="352" height="172" class="size-full wp-image-4844" /></a><p class="wp-caption-text">Networkview observe Rigidbody</p></div>
<p>Also in the Inspector, tag the object as &#8220;<strong>Player</strong>&#8220;. </p>
<div id="attachment_4845" class="wp-caption aligncenter" style="width: 401px"><a href="http://3dgep.com/wp-content/uploads/2012/11/TagPlayer.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/TagPlayer.png" alt="Tag as Player" title="Tag as Player" width="391" height="120" class="size-full wp-image-4845" /></a><p class="wp-caption-text">Tag as Player</p></div>
<p>Finally, drag the cube from the <strong>Hierarchy</strong> view into the <strong>Project</strong> view. This will create a prefab called &#8220;<strong>Player</strong>&#8221; in the project&#8217;s Assets folder. Move this prefab into the <strong>Game</strong> folder and delete the original <strong>Player</strong> GameObject from the scene.</p>
<p>In the &#8220;<strong>Game</strong>&#8221; folder add a JavaScript asset called &#8220;<strong>PlayerInfo.js</strong>&#8221; with the following code:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="ServerPlayerManager.js">
#pragma strict
var playerPrefab : GameObject;
</pre>
</div>
<p>Drag this script from the <strong>Project</strong> view onto the <strong>GameController</strong> object in the <strong>Hierarchy</strong> view. Select the <strong>GameController</strong> to view the <strong>Player Info</strong> (Script) in the <strong>Inspector</strong>. Now drag the &#8220;<strong>Player</strong>&#8221; prefab from the <strong>Project</strong> view onto the &#8220;<strong>Player Prefab</strong>&#8221; property in the <strong>Inspector</strong>. This script serves as a &#8220;global&#8221; placeholder for the player prefab that the clients will instantiate when they connect.</p>
<div id="attachment_4851" class="wp-caption aligncenter" style="width: 352px"><a href="http://3dgep.com/wp-content/uploads/2012/11/PlayerPrefab.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/PlayerPrefab.png" alt="Player prefab property in Inspector" title="Player prefab property in Inspector" width="342" height="62" class="size-full wp-image-4851" /></a><p class="wp-caption-text">Player prefab property in Inspector</p></div>
<p>We have now finished the shared &#8220;<strong>Game</strong>&#8221; folder. All that is left to do is to export the folder and (later) import it into the client project. To do this, select and right-click the &#8220;<strong>Game</strong>&#8221; folder in the <strong>Project</strong> view and select &#8220;<strong>Export Package&#8230;</strong>&#8221;  from the pop-up menu that appears. </p>
<p>The <strong>Exporting Package</strong> dialog will appear.</p>
<div id="attachment_4854" class="wp-caption aligncenter" style="width: 589px"><a href="http://3dgep.com/wp-content/uploads/2012/11/ExportPackage.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/ExportPackage.png" alt="Export package" title="Export package" width="579" height="389" class="size-full wp-image-4854" /></a><p class="wp-caption-text">Export package</p></div>
<p>Click the &#8220;<strong>Export&#8230;</strong>&#8221; button and save the Unity package as &#8220;<strong>NetworkGame</strong>&#8220;.</p>
<p>We will continue with the client project later on, but first we will complete the server side. </p>
<span id="Spawn_players"><h3>Spawn players</h3></span>
<p>In the folder &#8220;<strong>Server</strong>&#8220;, add a second JavaScript called <strong>ServerPlayerManager.js</strong>. The <strong>Project</strong> view should now look like the screenshot below.</p>
<div id="attachment_4849" class="wp-caption aligncenter" style="width: 304px"><a href="http://3dgep.com/wp-content/uploads/2012/11/ProjectView.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/ProjectView.png" alt="Project view" title="Project view" width="294" height="182" class="size-full wp-image-4849" /></a><p class="wp-caption-text">Project view</p></div>
<p>Add the following code to the <strong>ServerPlayerManager.js</strong> script:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="ServerPlayerManager.js">
#pragma strict

function spawnPlayer(player : NetworkPlayer) {
	var ply : PlayerInfo = GameObject.FindObjectOfType(PlayerInfo);
	var go : GameObject = Network.Instantiate(ply.playerPrefab, Vector3.up*3, Quaternion.identity, 0);
}

</pre>
</div>
<p>This code finds the <strong>PlayerInfo</strong> script (global placeholder) we created above and uses it to <strong>Network instantiate</strong> the <strong>Player</strong> prefab (the cube), positioning it 3 units above the plane (<strong>Vector3.up*3</strong>) so that it will initially drop down to the plane (it&#8217;s a rigid body, so it will be affected by physics). The cube is not rotated (<strong>Quaternion.identity</strong>). The group parameter is set to 0 which means send to all clients (we are not using groups).</p>
<p>To make sure the <strong>spawnPlayer()</strong> function is called, we add the following code to <strong>ServerMain.js</strong>:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="ServerMain.js">
@script RequireComponent(ServerPlayerManager)
private var spm : ServerPlayerManager;
function Awake() {
	spm = gameObject.GetComponent(ServerPlayerManager);
}

function OnPlayerConnected(player: NetworkPlayer) {	
	spm.spawnPlayer(player);
}
</pre>
</div>
<p>This code first ensures that the <strong>ServerMain.js</strong> script is attached to a <strong>GameObject</strong> that also has the <strong>ServerPlayerManager.js</strong> script attached to it. This is done by:</p>
<pre>
@script RequireComponent(ServerPlayerManager)
</pre>
<p>When the script is created, Unity calls the Awake() function and a reference to the <strong>ServerPlayerManager</strong> component is stored in a private variable:</p>
<pre>
private var spm : ServerPlayerManager;
function Awake() {
	spm = gameObject.GetComponent(ServerPlayerManager);
}
</pre>
<p>This private variable is used to call the <strong>spawnPlayer()</strong> function when a new client connects (Unity will invoke the <strong>OnPlayerConnected()</strong> function when a client connects to the server):</p>
<pre>
function OnPlayerConnected(player: NetworkPlayer) {	
	spm.spawnPlayer(player);
}
</pre>
<p>To finish the server side, drag both the <strong>ServerMain.js</strong> and <strong>ServerPlayerManager.js</strong> scripts onto the <strong>GameController</strong> object.</p>
<span id="Client_Project"><h2>Client Project</h2></span>
<p>Switch to the client project and create a folder called &#8220;<strong>Client</strong>&#8221; in the <strong>Project</strong> view. This folder will contain everything that is needed only on the client side. Drag the <strong>ClientMain.js</strong> script into this folder. Also, delete the GameObject in the scene.</p>
<p>Now import the <strong>NetworkGame.unitypackage</strong> you exported from the server project. To do this right click in the <strong>Project</strong> view and select <strong>Import Package > Custom Package&#8230;</strong> from the pop-up menu, then browse to the location you exported the package to.</p>
<div id="attachment_4863" class="wp-caption aligncenter" style="width: 580px"><a href="http://3dgep.com/wp-content/uploads/2012/11/ImportCustomPackage.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/ImportCustomPackage.png" alt="Import custom package" title="Import custom package" width="570" height="282" class="size-full wp-image-4863" /></a><p class="wp-caption-text">Import custom package</p></div>
<p>Open up the <strong>Game</strong> scene, and drag the <strong>ClientMain.js</strong> on to the <strong>GameController</strong> object in the <strong>Hierarchy</strong> view.</p>
<span id="Second_Networking_Solution"><h2>Second Networking Solution</h2></span>
<p>Press run in the server project and press the &#8220;<strong>Start Server</strong>&#8221;  button. Now press run in the client project and press on the &#8220;<strong>Connect to Server</strong>&#8221; button. You should see a cube drop down onto the plane in both the server and client game views.</p>
<div id="attachment_4864" class="wp-caption aligncenter" style="width: 460px"><a href="http://3dgep.com/wp-content/uploads/2012/11/GameViewInstantiatedPlayer.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/GameViewInstantiatedPlayer.png" alt="Client side game view instantiated player" title="Client side game view instantiated player" width="450" height="363" class="size-full wp-image-4864" /></a><p class="wp-caption-text">Client side game view instantiated player</p></div>
<p>Select the Player(clone) in server scene hierarchy and use the inspector to modify the position (change the x to 3 for example). You should see the cube change position on both the server and the client.</p>
<p>Select the Player(clone) in the client scene hierarchy and change it&#8217;s position likewise. The cube should now only be modified on the client side, and not the server side. In fact, if you now change the server side position again, the client side will jump to the correct (server) position again.</p>
<p>This clearly demonstrates that the server is authorative.</p>
<span id="Spawning_madness"><h2>Spawning madness</h2></span>
<p>In the client game view, press the &#8220;Disconnect&#8221; button. You will notice that the cube on the server and the client side remain where they are. Press the &#8220;Connect to Server&#8221; button again. You should see one additional cube spawn on the server side and <em>two</em> additional cubes on the client side, making the total number of cubes on the client side three.</p>
<p>If you repeat this a couple of times, you will soon have cubes exploding all over the place!</p>
<p>To understand why this is happening, we first need to discuss Remote Procedure Calls (RPC) and how they are implemented in Unity.</p>
<span id="RPCs"><h1>RPCs</h1></span>
<p>Remote Procedure Calls, or <a href="http://docs.unity3d.com/Documentation/Components/net-RPCDetails.html" title="Unity Remote Procedure Calls" target="_blank">RPCs</a> for short, are function calls made over the Network. This allows a client to call a function on a remote server, or vice versa, for example. </p>
<p>The following code snippet demonstrates an RPC function:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="Javascript snippet">
@RPC
function PrintText (text : String)
{
    Debug.Log(text);
}
</pre>
</div>
<p>Notice the @RPC attribute placed before the function declaration. This tells Unity that this function can be called remotely. </p>
<p>To call this function, the server or any client can use:</p>
<pre>
networkView.RPC ("PrintText", RPCMode.All, "Hello world");
</pre>
<p>The first parameter of the RPC() call is simply the name of the function to call. The third parameter is the parameter for the function call, i.e. the above call is equivalent to locally calling <em>PrintText(&#8220;Hello world&#8221;)</em>.<br />
The second parameter is the RPCMode, which can be used to indicate to whom the RPC call should be made:</p>
<ul>
<li><strong>Server</strong>: Sends to the server only.</li>
<li><strong>Others </strong>: Sends to everyone except the sender</li>
<li><strong>OthersBuffered</strong> : Sends to everyone except the sender and adds to the buffer</li>
<li><strong>All</strong> : Sends to everyone</li>
<li><strong>AllBuffered	</strong>: Sends to everyone and adds to the buffer</li>
</ul>
<span id="Buffered_RPCs"><h2>Buffered RPCs</h2></span>
<p>The RPCMode allows an RPC call to be either unbuffered (Server, Others, All) or buffered (OthersBuffered, AllBuffered). Non buffered calls are carried out and then forgotten. Buffered calls, on the other hand, are never lost but are stored by the server in an ordered stack. When a new client connects, all the buffered calls are carried out on the new client (in order). This allows the game state to recreated on a client who comes into a game that has already started.</p>
<p>Whenever we make a call to Network.Instantiate(), Unity makes use of buffered RPCs underwater. This ensures that when new clients connect, all the instantiated game objects (player instances etc.) will also be created on the new client.</p>
<span id="Restrictions_on_RPCs"><h2>Restrictions on RPCs</h2></span>
<p>You can easily build your own RPCs, but there are some restrictions:</p>
<ul>
<li>Firstly, the network communication required for RPCs is handled by a NetworkView. This means that the script containing RPC functions must be attached to a GameObject that also has a NetworkView component. This is why we added a NetworkView to the GameController object in the projects above. The GameController is a dummy placeholder and so we don&#8217;t need to synchronise the state (position, rotation etc) of the object. However, the script calling Network.Instantiate() (and thus making RPC calls underwater) is attached to the GameController. For this reason, it requires a NetworkView, but the State Synchronisation property can be set to &#8220;off&#8221;  and the Observed property to &#8220;None&#8221;.
</li>
<li>Secondly, an RPC function can have as many parameters as you want, but each parameter must be one of the following types: <strong>float, string, NetworkPlayer, NetworkViewID, Vector3, Quaternion</strong>. To call an RPC with more than one parameter, use the following syntax:
<pre>
networkView.RPC ([rpc function name], [rpc mode], parameter1, parameter2, ...);
</pre>
</li>
</ul>
<span id="Improved_Spawning"><h1>Improved Spawning</h1></span>
<p>Returning to our client and server projects, we can easily understand the spawning madness we get when the client disconnects and reconnects. When the client connects for the first time, its Intantiate() call is buffered. When the client disconnects and connects again, it triggers a new Instantiate() and it also gets the buffered Instantiate(), thus leading to two cubes. A third connect, would lead to three cubes, and so on.</p>
<p>To avoid this problem, the server needs to clean up the buffered RPC calls for clients that have disconnected.</p>
<p>However, that is not all. On the client side, the client has to clean up its old cubes before connecting again. The sever cannot do it for the client because it is no longer connected. </p>
<span id="Clean_up_client_side"><h2>Clean up client side</h2></span>
<p>To improve the spawning process add the following code to the client side:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="ClientMain.js">
function OnDisconnectedFromServer (info : NetworkDisconnection) {
	var gos : GameObject[] = GameObject.FindGameObjectsWithTag("Player");
	for(var go : GameObject in gos) {
		Destroy(go);
	}
}
</pre>
</div>
<p>The function OnDisconnectedFromServer() will be called by Unity when the client is disconnected from the server. Because we tagged the Player prefab with the &#8220;Player&#8221; tag, we can get any cube instances using:</p>
<pre>
GameObject.FindGameObjectsWithTag("Player");
</pre>
<p>We can then use the Destroy() function to delete these old player cubes.</p>
<span id="Clean_up_server_side"><h2>Clean up server side</h2></span>
<p>To improve the server side spawning and cleaning up when a client disconnects is a little more complicated. The reason for this is that the server needs to keep track of which cube instance belongs to which client. This allows the server to delete the right cube when a client disconnects.</p>
<p>Replace the existing code in ServerPlayerManager.js with:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="ServerPlayerManager.js">
#pragma strict

var players = new Hashtable();

function spawnPlayer(player : NetworkPlayer) {
	var ply : PlayerInfo = GameObject.FindObjectOfType(PlayerInfo);
	var go : GameObject = Network.Instantiate(ply.playerPrefab, Vector3.up*3, Quaternion.identity, 0);
	players[player] = go;
}
</pre>
</div>
<p>This instantiates a new cube when a client connects, and places the cube instance in a hashtable, using the NetworkPlayer as the key.</p>
<p>To clean up when a client disconnects add the following code:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="ServerPlayerManager.js">

function deletePlayer(player : NetworkPlayer) {
 	var go : GameObject = players[player];
 	Network.RemoveRPCs(go.networkView.viewID); 
	Network.Destroy(go); 
	players.Remove(player); 
}
</pre>
</div>
<p>This function first finds the cube instance for this player in the hastable (using the NetworkPlayer as key). It then calls</p>
<pre>
Network.RemoveRPCs(go.networkView.viewID);
</pre>
<p>which clears away any buffered RPCs belonging to the cube&#8217;s NetworkView. This will ensure that new clients connecting will not instantiate a cube for the disconnected player.<br />
Next, the cube is deleted from all clients (including the server) using</p>
<pre>
Network.Destroy(go); 
</pre>
<p>This is basically the network version of the local Destroy() function.<br />
Finally, the server removes the player and cube instance from the hashtable:</p>
<pre>
players.Remove(player);
</pre>
<p>To make sure this function is called when a client disconnects, as the following code the ServerMain.js</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="ServerMain.js">
function OnPlayerDisconnected(player : NetworkPlayer) {
	spm.deletePlayer(player);
}

</pre>
</div>
<p>This uses the private variable instance of the ServerPlayerManager.js script initialised earlier.</p>
<span id="Run_the_solution"><h2>Run the solution</h2></span>
<p>Start up the Server and the Client projects, and try connecting and reconnecting the client. Spawning and cleaning up of the cubes should now work as expected. Try building the client to create an executable (.exe) and also running this a number of times so that you have more than one client connecting to the server at the same time.</p>
<span id="Movement"><h1>Movement</h1></span>
<p>To complete this introduction tutorial, lets improve our networking solution to allow the clients to move their cubes about. To do this in an authorative server solution requires the clients to send their input (key presses etc) to the server. The server will then update the world (ie the position of the clients cube) and send the result to all connected clients.</p>
<span id="Server_project"><h2>Server project</h2></span>
<p>Add the following code to ServerPlayerManager.js:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="ServerPlayerManager.js">
@RPC
function handlePlayerInput(player: NetworkPlayer, vertical: float, horizontal: float) {
 	var go : GameObject = players[player];
 	go.transform.position = go.transform.position + Vector3.right*horizontal;
 	go.transform.position = go.transform.position + Vector3.forward*vertical;
}
</pre>
</div>
<p>This is an RPC function which can be called by the clients remotely. It basically finds the cube belonging to the player and then updates the position depending on the value of the &#8220;vertical&#8221; and &#8220;horizontal&#8221; parameters the client sends.</p>
<span id="Client_project"><h2>Client project</h2></span>
<p>Add the following code to ClientMain.js:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="ClientMain.js">
function Update() {
	if(Input.anyKey) {
		sendInputToServer();
	}
}

function sendInputToServer() {
	var vertical: float = Input.GetAxis("Vertical");
	var horizontal: float = Input.GetAxis("Horizontal");
    if((vertical!=0)||(horizontal!=0)) {
        networkView.RPC("handlePlayerInput",RPCMode.Server,Network.player,vertical, horizontal);
    }
}

</pre>
</div>
<p>Unity <a href="http://docs.unity3d.com/Documentation/ScriptReference/Input.html" title="Unity Input" target="_blank">Input</a> is used to check if any key is pressed</p>
<pre>
if(Input.anyKey)
</pre>
<p>and if so the function sendInputToServer() is called. This function uses <a href="http://docs.unity3d.com/Documentation/ScriptReference/Input.GetAxis.html" title="Unity Input GetAxis" target="_blank">Input.GetAxis()</a> to check for input:</p>
<pre>
var vertical: float = Input.GetAxis("Vertical");
var horizontal: float = Input.GetAxis("Horizontal");
</pre>
<p>On the &#8220;Horizontal&#8221; axis, -1 is left and 1 is right. On the &#8220;Vertical&#8221; axis, 1 is up and -1 is down. If theri is any input (!=0) then the code calls the RPC &#8220;handlePlayerInput&#8221; on the server: </p>
<pre>
networkView.RPC("handlePlayerInput",RPCMode.Server,Network.player,vertical, horizontal);
</pre>
<p>passing along as first parameter the client NetworkPlayer</p>
<pre>
Network.player
</pre>
<p>followed by the values of vertical and horizontal.</p>
<p>Note that RPCMode.Server is used, meaning that the RPC call should only be sent to the server for execution.</p>
<p>Also add the following code:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="ClientMain.js">
@RPC
function handlePlayerInput(player: NetworkPlayer, vertical: float, horizontal: float) {
}
</pre>
</div>
<p>The reason that this dummy (empty) function is needed is that Unity requires the client and the server to both have the RPC function, even if it is only going to be called on the server. This is a typical for Unity networking in that Unity seems to prefer the client and server code to be combined into one and the same project. This would favour the peer to peer networking model, where a client can host a game and be the server as well. In this tutorial, we have split the client and sever code into two projects. This serves the purpose of clarifying what the server does and what the client does.</p>
<span id="Final_run"><h2>Final run</h2></span>
<p>Run the server and connect with one or more clients. Each client should now be able to move it&#8217;s own cube (but nobody else&#8217;s). The server should not be able to move anything. Try bumping one cube into another and see that the server side physics (the cubes are rigid bodies) handles all the collisions.</p>
<p>Congratulations! You have now completed this introduction to Unity networking. </p>
<span id="Download"><h1>Download</h1></span>
<p>You can download the two projects directly <a href="http://3dgep.com/wp-content/uploads/2012/12/NetworkTutorial.zip" title="Unity Networking Tutorial">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://3dgep.com/?feed=rss2&#038;p=4609</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>An Introduction to Unity Shaders</title>
		<link>http://3dgep.com/?p=4622</link>
		<comments>http://3dgep.com/?p=4622#comments</comments>
		<pubDate>Mon, 10 Dec 2012 23:24:07 +0000</pubDate>
		<dc:creator>TomJansen</dc:creator>
				<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://3dgep.com/?p=4622</guid>
		<description><![CDATA[In this article, I will give a basic introduction to what shaders are, discuss the basics of the Unity rendering pipeline and introduce the reader how to use shaders within the Unity game engine. Introduction Shaders are used a lot &#8230; <a href="http://3dgep.com/?p=4622">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="attachment_4569" class="wp-caption alignleft" style="width: 160px"><a href="http://3dgep.com/wp-content/uploads/2012/12/surfaceshader.png"><img class="size-full wp-image-4569  " title="Surface Shader" src="http://3dgep.com/wp-content/uploads/2012/12/surfaceshader.png" alt="Surface Shader" width="150" height="150" /></a><p class="wp-caption-text">Surface Shader</p></div>
<p>In this article, I will give a basic introduction to what shaders are, discuss the basics of the Unity rendering pipeline and introduce the reader how to use shaders within the Unity game engine.</p>
<p><span id="more-4622"></span></p>
<div style="clear: both;"><div class='toc wptoc'>
<h2>Table of Contents</h2>
<ol class='toc-odd level-1'>
	<li>
		<a href="#Introduction">Introduction</a>
	</li>
	<li>
		<a href="#Shaders_in_Unity">Shaders in Unity</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Surface_Shaders">Surface Shaders</a>
			</li>
			<li>
				<a href="#Vertex_and_Fragment_Shaders">Vertex and Fragment Shaders</a>
			</li>
			<li>
				<a href="#Fixed_Function_Shaders">Fixed Function Shaders</a>
			</li>
		</ol>
	<li>
		<a href="#Unitys_rendering_pipeline">Unity's rendering pipeline</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Vertex_Lit">Vertex Lit</a>
			</li>
			<li>
				<a href="#Forward_Rendering">Forward Rendering</a>
			</li>
			<li>
				<a href="#Deferred_Rendering_">Deferred Rendering </a>
			</li>
		</ol>
	<li>
		<a href="#ShaderLab">ShaderLab</a>
	</li>
	<li>
		<a href="#Fixed_function_shaders">Fixed function shaders</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Shader">Shader</a>
			</li>
			<li>
				<a href="#Properties">Properties</a>
			</li>
			<li>
				<a href="#SubShader">SubShader</a>
			</li>
			<li>
				<a href="#Tags">Tags</a>
			</li>
			<li>
				<a href="#Fallback">Fallback</a>
			</li>
			<li>
				<a href="#Category">Category</a>
			</li>
		</ol>
	<li>
		<a href="#Vertex_and_fragment_shaders">Vertex and fragment shaders</a>
	</li>
	<li>
		<a href="#Surface_shaders">Surface shaders</a>
	</li>
	<li>
		<a href="#Conclusion">Conclusion</a>
	</li>
	<li>
		<a href="#References">References</a>
	</li>
	<li>
		<a href="#Images_Used">Images Used</a>
	</li>
	<li>
		<a href="#Suggested_reading:">Suggested reading:</a>
	</li>
	<li>
		<a href="#Download_Unity_Project">Download Unity Project</a>
	</li>
</ol>
</div>
<div class='wptoc-end'>&nbsp;</div></div>
<span id="Introduction"><h1>Introduction</h1></span>
<p style="text-align: left;">Shaders are used a lot in video games to produce a wide variety of effects like for example lightning models, distortion, (motion)blur, bloom, and edge detection effects. A shading language is used to program the graphics processing unit (gpu) and allows the user to setup the graphics hardware for rendering instead of the fixed function pipeline. There are 3 shaders types commonly used; Vertex Shaders, Fragment Shaders and Geometry Shaders.</p>
<p>In Unity the user is able to write custom shaders, however full screen effects require render textures which are only available in Unity Pro and won’t be covered in this article. These are full screen image processing effects are a pretty advanced topic on themselves. Because there is quite a lot of material to cover I won’t be delving too deep into writing custom shader effects but emphasize on what shaders are and how they are used in the Unity game engine.</p>
<div id="attachment_4941" class="wp-caption alignnone" style="width: 497px"><a href="http://3dgep.com/wp-content/uploads/2012/12/Borderlands2CellShading.png"><img class="size-full wp-image-4941" title="Borderlands2 Cell Shading" src="http://3dgep.com/wp-content/uploads/2012/12/Borderlands2CellShading.png" alt="Borderlands2 Cell Shading" width="487" height="277" /></a><p class="wp-caption-text">Borderlands 2 Cell Shading</p></div>
<span id="Shaders_in_Unity"><h1>Shaders in Unity</h1></span>
<p>In Unity all rendering is done through the use of shaders. Shaders in Unity are small scripts that allow the user to configure how the graphics hardware is set up for rendering. Unity ships with over 60 built-in shaders that are are used through the use of materials. There is a close relationship in Unity between materials and shaders. The shaders contain the code that defines what kind of properties and asset to use while materials allow the user to adjust the properties and assign assets. For example if we create a new GameObject and assign a material to it, we can choose a shader from the Inspector that specifies how our material should look like when we are in-game. The properties of the material vary depending on the shader that is used to render the GameObject.</p>
<p>There are 3 ways how shaders can be written in Unity; <strong>Fixed Function Shaders, <strong>Vertex and Fragment </strong></strong>Shaders<strong><strong>, </strong></strong>and<strong> Surface Shaders</strong>. The code for these shaders is encapsulated using the Unity shading and material language called <strong>‘ShaderLab’</strong>. The shaders themselves are typically written using <strong>CG</strong> or <strong>HLSL</strong> shading language.</p>
<span id="Surface_Shaders"><h2>Surface Shaders</h2></span>
<p><strong>Surface shaders</strong> are commonly used if your shader needs to be affected by both lights and shadows. Since the shader needs to be affected by light, you do not want to write out the complete shader code that handles a default BlinnPhong lighting model every time. This allows the user to write more complex shaders in a more compact way. If the shader doesn&#8217;t need to interact with lighting it is best to use a vertex and fragment shader instead. Otherwise Unity would still be making lighting calculations while we don&#8217;t need them.</p>
<span id="Vertex_and_Fragment_Shaders"><h2>Vertex and Fragment Shaders</h2></span>
<p><strong>Vertex and fragment shaders </strong>can be used if the shader doesn&#8217;t need to interact with lighting or when you need to deal with an effect that a surface shader can’t handle. These are the most flexible shaders to create shader effects however it makes it harder to interact with lighting.</p>
<span id="Fixed_Function_Shaders"><h2>Fixed Function Shaders</h2></span>
<p><strong>Fixed function shaders </strong>are used for older hardware that doesn&#8217;t support programmable shaders. The fixed function shaders are usually used as a last fallback to make sure a game is still rendering something meaningful when a certain shader effect is not supported by the graphics processing unit. Fixed function shaders are completely written using in Unity&#8217;s &#8216;<strong>ShaderLab&#8217;</strong>. We will look at this in more detail later.</p>
<div class="wp-caption alignleft" style="width: 560px"><img title="UnityBuildInShaders" src="http://docs.unity3d.com/Documentation/Images/manual/Materials-1.jpg" alt="" width="550" height="235" /><p class="wp-caption-text">Unity&#8217;s Built-In Shaders</p></div>
<span id="Unity8217s_rendering_pipeline"><h1>Unity&#8217;s rendering pipeline</h1></span>
<p>So with shaders we can define how our object will appear in the game world and how it will react to lighting. How these lights will react on the objects depend on the <strong>passes</strong> of the shader and which <strong>rendering path </strong>is used. The rendering path can be changed through <strong>Unity’s Player Settings</strong>. Or it can be overridden in the camera&#8217;s<strong> ‘Rendering Path’</strong> setting in the inspector. In Unity there are 3 rendering paths: <strong>Vertex Lit,</strong> <strong>Forward Rendering</strong> and <strong>Deferred Rendering</strong>. If the graphics card can’t handle the current selected render path it will fallback and use another one. So for example if deferred rendering isn&#8217;t supported by the graphics card, Unity will automatically use Forward Rendering. If forward rendering is not supported it will change to Vertex Lit. Since all shaders are influenced by the rendering path that is set I will briefly describe what each rendering path does.</p>
<span id="Vertex_Lit"><h2>Vertex Lit</h2></span>
<p><strong>Vertex Lit</strong> is the simplest lighting mode available. It has no support for real-time shadows. It is commonly used on old computers with limited hardware. Internally it will calculate lighting from all lights at the object vertices in one pass. Since lighting is done on a per-vertex level, per-pixel effects are not supported.</p>
<span id="Forward_Rendering"><h2>Forward Rendering</h2></span>
<p><strong>Forward rendering</strong> renders each object in one or more passes, depending on the lights that affect the object. All lights are treated differently depending on the settings and intensity being set by the user. When forward rendering is used, the amount of pixel lights set from the quality menu that affect the object will be rendering using full per-pixel lighting. Additionally 4 point lights are calculated per-vertex and all other lights are computed as Spherical Harmonics which is an approximation. A light can be per-pixel lit depending on several situations. Lights with the render mode set to <em>Not Important</em>, are always per-vertex or spherical harmonics. Brighter lights are always calculated per-pixel also when the render mode is set to <em>Important</em>. Forward rendering is the default selected rendering path in Unity.</p>
<span id="Deferred_Rendering_"><h2>Deferred Rendering </h2></span>
<p>In <strong>Deferred rendering</strong> there is no limit on the number of lights that affect an object and all lights are calculated on a per-pixel base. This means that all lights interact with normal maps etc. Lights can also have cookies and shadows. Since all lights are calculated per-pixel it works great on big polygons. Deferred rendering is only available in Unity Pro.</p>
<div id="attachment_4958" class="wp-caption alignnone" style="width: 414px"><a href="http://3dgep.com/wp-content/uploads/2012/12/renderingpath.png"><img class="size-full wp-image-4958" title="Unity Rendering Path" src="http://3dgep.com/wp-content/uploads/2012/12/renderingpath.png" alt="Unity Rendering Path" width="404" height="427" /></a><p class="wp-caption-text">Selecting a rendering path</p></div>
<span id="ShaderLab"><h1>ShaderLab</h1></span>
<p>All shaders in Unity are wrapped in a material and shading language that is called ‘ShaderLab’. ShaderLab organizes the shader structure. Here is an example from the Unity documentation:</p>
<div class="notranslate">
<pre class="brush:cg;toolbar:false;first-line:1;" title="MyShader.shader">
Shader "MyShader" {
    Properties {
        _MyTexture ("My Texture", 2D) = "white" { }
        // other properties like colors or vectors 
        // go here as well
    }
    SubShader {
        // here goes the 'meat' of your
        //  - surface shader or
        //  - vertex and fragment shader or
        //  - fixed function shader
    }
    SubShader {
        // here goes a simpler version of the SubShader above that
        // can run on older graphics cards
    }
}
</pre>
</div>
<p>In ShaderLab we start by defining a name for the shader which in this case is “MyShader” and it will be listed in the inspector under that name. Next there are properties defined and these will be shown in the Material Inspector in Unity. Sub Shaders are used to create a list of shaders that can be used on different types of hardware. If the gpu doesn&#8217;t support a certain feature, it is able to fallback to a more simplified version of this shader. Unity itself will go through the list of sub shaders and pick the first sub shader that is supported by the hardware. <em>Note</em>: <em>The user must always specify at least 1 sub shader!</em></p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="">
Shader "example" {
    // properties and subshaders here...
    Fallback "otherexample"
}
</pre>
</div>
<p>Optionally the user can also define a <strong>fallback</strong> which tries to run another <strong>sub shader</strong> from another <strong>shader</strong>. The fallback gets called when all the sub shaders you defined are not able to run on the hardware. This is nice since we don’t need to rewrite all the sub shader code from another shader.</p>
<div class="my-note">
Shaders are automatically compiled by the Unity editor once you have edited them. Because shaders are compiled by the editor you cannot create shaders from scripts at run-time.</div>
<span id="Fixed_function_shaders"><h1>Fixed function shaders</h1></span>
<p>To start, I will show you how to create a new fixed function shader that binds a color property for a material and after that we will walk through Unity’s vertex lit shader. We can create a new shader from the project panel in Unity by pressing Create &#8211; Shader or from the top menu In Unity under<em> Assets &#8211; Create &#8211; Shader</em>. If we want to edit a shader we can simply double click it in the project view similar to opening a script file. Once we double-clicked a shader, Unity will open <strong>MonoDevelop</strong> to start editing the shader file. After the shader is opened we first want to delete everything that Unity created by default. Unity by default creates a basic template for a surface shader. We can recognize if it is a fixed function shader if we take a look at the inspector when selecting a shader in the project view under Vertex and Pixel program.</p>
<div id="attachment_4962" class="wp-caption alignnone" style="width: 624px"><a href="http://3dgep.com/wp-content/uploads/2012/12/FixedFunctionShader.png"><img class="size-full wp-image-4962" title="Fixed Function Shader" src="http://3dgep.com/wp-content/uploads/2012/12/FixedFunctionShader.png" alt="Fixed Function Shader" width="614" height="261" /></a><p class="wp-caption-text">Fixed Function Shader</p></div>
<span id="Shader"><h2>Shader</h2></span>
<p>First we need to start by giving our shader a name. Look at the ShaderLab body above to see the basic layout of the ShaderLab structure. We can use <strong>backslashes</strong> in the Shader name to put the shader in a <strong>custom folder</strong> in the inspector. It should look like this:</p>
<div class="notranslate">
<pre class="brush:cg;toolbar:false;first-line:1;">
Shader “Custom/MyCustomShader” {
}
</pre>
</div>
<span id="Properties"><h2>Properties</h2></span>
<p>Next we need to define some properties that we want to tweak in the material inspector. First we start with the keyword ‘Properties’ and use opening brackets so we can list several properties we want. Properties can be used by the shader, so for example we could set a color and a texture and combine those two together which will be the final color of our material.</p>
<p>Let’s take a look at an example of a property.</p>
<div class="notranslate">
<pre class="brush:cg;toolbar:false;first-line:1;">
Properties {
    _Color ("Main Color", Color) = (1.0, 1.0, 1.0, 1.0)
}
</pre>
</div>
<p>First the name of the property is set in this case _Color. Next we need to specify a display name; this is how the property will be listed in the material inspector. Next we specify the type of property we want to set and we need to assign an actual value to that property we just specified. In our case it is a Color, which takes 4 floats (RGBA). Instead of the Color property we can also add different types. For example: Range, 2D, Rect, Cube, Float, and Vector. Range is presented as a slider in the material inspector and goes from min to max. 2D takes a string as parameter and defines a 2D texture. Rect defines a rectangle (non-power of two) texture. Cube defines a cubemap texture, float defines a floating point property and Vector defines a four component vector. The texture property can also be given property options which can for example set the texture coordinate generation of this texture.</p>
<span id="SubShader"><h2>SubShader</h2></span>
<p>Now we need to define at least one sub shader so our object can be displayed. As stated above Unity will pick the first sub shader that runs on the graphics card. Each sub shaders defines a list of rendering passes. Each pass causes the geometry to be rendered once. Generally speaking you would like to use the minimum amount of passes possible since which every added pass our performance goes down because of the object being rendered again. A pass can defined in 3 ways, a <strong>regular pass</strong>, <strong>use pass</strong> or <strong>grab pass</strong>. The ‘<em>UsePass’</em> command is used when we want to use another pass from another shader. This can help by reducing code duplication. ‘<em>GrabPass’</em> is a special pass. It grabs the content of the screen where the object is to be drawn into a texture. This texture can then be used for more advanced image based processing effects. A regular pass sets various states for the graphics hardware. For example we could turn on/off vertex lighting, set blending mode, or set fog parameters.</p>
<div class="notranslate">
<pre class="brush:cg;toolbar:false;first-line:1;">
SubShader {
    Pass {
        Material {
            Diffuse [_Color]
        }
    }
    Lighting On
}
</pre>
</div>
<p>The material block binds the property values we set for _Color to the fixed function lighting material settings. The command Lighting On turns on the standard per-vertex lighting.</p>
<span id="Tags"><h2>Tags</h2></span>
<p>Additionally tags can be setup which tells how and when sub shaders should be rendered to the rendering engine. Tags must be specified inside the sub shader block and not inside the pass block.</p>
<span id="Fallback"><h2>Fallback</h2></span>
<p>A fallback will automatically be used when none of the previously described sub shaders are able to run on the hardware and it will try to use a sub shader from another shader.</p>
<span id="Category"><h2>Category</h2></span>
<p>Categories can be used to group multiple shaders inheriting the same rendering state. For example the user can group several sub shaders to with all of them having Fog turned off.</p>
<div id="attachment_4965" class="wp-caption alignnone" style="width: 744px"><a href="http://3dgep.com/wp-content/uploads/2012/12/FixedFunctionColor.png"><img class="size-full wp-image-4965" title="Fixed Function Color" src="http://3dgep.com/wp-content/uploads/2012/12/FixedFunctionColor.png" alt="Fixed Function Color" width="734" height="372" /></a><p class="wp-caption-text">A fixed function shader assigning a Color type</p></div>
<span id="Vertex_and_fragment_shaders"><h1>Vertex and fragment shaders</h1></span>
<p>When using vertex and fragments shaders the so called ‘Fixed Function Pipeline’ is turned off. As an example the 3D transformations that normally take place are disabled. This means that when we want to write a vertex/fragment program we need to rewrite the fixed function functionality ourselves that is normally built into API’s like OpenGL. Note that vertex and fragment shaders are typically used when the shader doesn’t need to interact with lighting. If that is the case a ‘Surface shader’ is suggested.</p>
<p>In Unity shaders in ShaderLab are written using the Cg programming language. ‘Cg Snippets’ are compiled into low-level shader assembly by the Unity editor. That means that once you distribute your game files, only the low-level assembly code will be included. This is how a general ‘Cg Snippet’ would look in ShaderLab:</p>
<div class="notranslate">
<pre class="brush:cg;toolbar:false;first-line:1;">
Pass {
    // ... the usual pass state setup ...

    CGPROGRAM
    // compilation directives for this snippet, e.g.:
    #pragma vertex vert
    #pragma fragment frag

    // the Cg code itself

    ENDCG
    // ... the rest of pass setup ...
}
</pre>
</div>
<p>The whole Cg code is placed inside the Pass block between <strong>CGPROGRAM</strong> and <strong>ENDCG</strong> keywords. The <strong>pragma</strong> <strong>directives</strong> indicate what function should be executed for the <strong>vertex</strong> program, and another function that is executed for the <strong>fragment</strong> program. In this case ‘<em>vert’</em> is the vertex program and ‘<em>frag’</em> is the fragment program. The vertex program is executed at a per-vertex level, where the fragment program is executed at a per-pixel level. Unity also contains several files that bring predefined variables and helper functions. This is done by the standard include directive like &#8211; <em>#include “UnityCG.cginc”</em>.</p>
<p>Similarly to the fixed function shaders we can specify properties that should be revealed in the material inspector. To use these variables in your ‘<strong>Cg Snippets</strong>’ we need to define a variable that has a matching name and a matching type. Unity will automatically set the variable for us as long the name and type are matched with the property. This means that if you defined a Property called _Color (“Main Color”, Color) in the Properties block you need to have a matching Color type named _Color. In this case a float4 would be the correct type to use since a Color consists out of 4 floating point numbers.</p>
<p><em>Note: the syntax might not look familiar to you. In case you want to learn more about the Cg programming language, I suggest heading over to the NVIDIA website. I added a few resource pages at the end of this article.</em></p>
<span id="Surface_shaders"><h1>Surface shaders</h1></span>
<p>Surface shaders in Unity are an easy way to write shaders that make use of lighting instead of using low-level vertex and pixel shaders. Surface shaders are still written in Cg/HLSL. The surface shader compiler will turn the surface shader into the actual <strong>vertex</strong> and <strong>pixel</strong> shaders as well as the rendering passes to handle forward and deferred rendering. Using surface shaders prevents the user from typing repetitive code that calculates lighting.</p>
<p>The user needs define a surface function that describes the standard output of the surface shader which describes properties of the surface like albedo color, normal, emission value, specularity and so on. This is how an output structure would look like:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
struct SurfaceOutput {
    half3 Albedo;
    half3 Normal;
    half3 Emission;
    half Specular;
    half Gloss;
    half Alpha;
};
</pre>
</div>
<p>A surface shader is placed in between a <strong>CGPROGRAM</strong> and an <strong>ENDCG</strong> block. It must be placed inside the SubShader block. To define a surface shader the user must use <strong>#pragma surface</strong> to indicate it is a surface shader. The complete pragma directive looks like this:</p>
<p><strong>#pragma surface surfaceFunction lightModel [optional parameters]</strong></p>
<p>The surface function indicates which surface shader function contains the Cg code. The function should have the following form: <strong>void surfaceFunction(Input IN, inout SurfaceOutput o)</strong></p>
<p>The <em>Input</em> or <em>IN</em> is a structure we should have defined. Input should contain any texture coordinates and extra automatic variable needed by the surface function <strong>surfaceFunction</strong>.  The <em>lightModel</em> specified which lighting model we want to use. There are several built-in lighting models available like <strong>Lambert</strong> (diffuse) and <strong>BlinnPhong</strong> (specular). For all list of all the optional parameters I suggest you read the Unity documentation on surface shaders which will be listed at the end of this article. The user is also able to write a custom lightModel that can be used in the surface shader however that won’t be described in this article.</p>
<p>The Input structure we need to specify usually has the texture coordinates that are needed by the shader. Texture coordinates must be named ‘<strong>uv’ </strong>followed by the texture name. We can also use ‘<strong>uv2’ </strong>to indicate we are dealing with a second texture coordinate set. There are several values that can be defined in the Input structure like view direction, screen/world position, world normal etc.</p>
<p>So let’s take a look at a simple diffuse surface shader from the Unity manual.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
Shader "Example/Diffuse Simple" {
    SubShader {
        Tags { "RenderType" = "Opaque" }
        CGPROGRAM
        #pragma surface surf Lambert
        struct Input {
            float4 color : COLOR;
        };
        void surf (Input IN, inout SurfaceOutput o) {
           o.Albedo = 1;
        }
        ENDCG
    }
    Fallback "Diffuse"
}
</pre>
</div>
<p>Probably you immediately notice that surface shaders are quite similar to the previously described fixed function shader except the surface shader has the additional lines we just described, like the #pragma directive indicating we are dealing with a surface shader here. So what is new here?</p>
<p>The most important change we see is that inside the SubShader<strong> </strong>block we start with <strong>CGPROGRAM</strong> and end the SubShader with <strong>ENDCG</strong>. All our <strong>Cg</strong> code will be placed within this block. After this we have the pragma directive to indicate this is surface shader. In this case we tell <em>surf</em> is our surface function and that the lighting model to use is Lambert.  Next there is an input structure defined. This shader only specified a color as input value.</p>
<p>After the input structure is created, the surface function is defined which takes the Input and a surface output as parameters. The output will be the actual output of the shader code. So in this case we can see that the <em>albedo</em> of the output is set to 1. This will result of this shader will be that the surface color will be set to white while it used the Lambert (diffuse) lighting model we defined in the pragma directive.</p>
<div id="attachment_4973" class="wp-caption alignnone" style="width: 758px"><a href="http://3dgep.com/wp-content/uploads/2012/12/SurfaceShaderChecker.png"><img class="size-full wp-image-4973" title="Surface Shader Checker" src="http://3dgep.com/wp-content/uploads/2012/12/SurfaceShaderChecker.png" alt="Surface Shader Checker" width="748" height="408" /></a><p class="wp-caption-text">A surface shader creating a checker pattern</p></div>
<span id="Conclusion"><h1>Conclusion</h1></span>
<p>Shaders are quite an advanced and complex subject and learning how to write shaders isn&#8217;t easy and something that you learn in one day. Hopefully I was able to give the reader a better understanding of the underlying rendering pipeline, how lighting is treated and how shaders can be used to manipulate the resulting outcome. You probably used materials all the time already, but hopefully you now have a better understanding of how they work internally. There is a lot of material to cover so I didn&#8217;t go into great detail of each render setting of a shader. I suggest you refer to the Unity Reference Manual for a more detailed look on shaders.</p>
<p>We learned:</p>
<ul>
<li>That shaders in ShaderLab are written using the Cg programming language.</li>
<li>That Unity utilizes different rendering pipelines.</li>
<li>How materials and shaders have a direct connection between them.</li>
<li>The differences between Fixed function, Vertex and Fragment, and Surface shaders.</li>
<li>That Surface Shaders are compiled into vertex and fragment shaders.</li>
<li>How all shader code is encapsulated in Unity’s ShaderLab.</li>
<li>That vertex/fragment shaders have two functions that describe both the vertex and fragment program.</li>
</ul>
<p>Furthermore we took a look at:</p>
<ul>
<li>How to write a basic ‘Fixed Function’ shader.</li>
<li>How surface shaders are being defined and what they can do.</li>
<li>How we can define a structure.</li>
</ul>
<span id="References"><h1>References</h1></span>
<p>The following references were used to gather the information required to write this article.</p>
<p><a href="http://docs.unity3d.com/Documentation/Manual/Materials.html" target="_blank">http://docs.unity3d.com/Documentation/Manual/Materials.html</a><br />
<a href="http://docs.unity3d.com/Documentation/Components/Built-inShaderGuide.html" target="_blank">http://docs.unity3d.com/Documentation/Components/Built-inShaderGuide.html</a><br />
<a href="http://docs.unity3d.com/Documentation/Manual/Shaders.html" target="_blank">http://docs.unity3d.com/Documentation/Manual/Shaders.html</a><br />
<a href="http://docs.unity3d.com/Documentation/Components/SL-Shader.html" target="_blank">http://docs.unity3d.com/Documentation/Components/SL-Shader.html</a><br />
<a href="http://docs.unity3d.com/Documentation/Components/SL-Reference.html" target="_blank">http://docs.unity3d.com/Documentation/Components/SL-Reference.html</a><br />
<a href="http://docs.unity3d.com/Documentation/Components/SL-SurfaceShaders.html" target="_blank">http://docs.unity3d.com/Documentation/Components/SL-SurfaceShaders.html</a><br />
<a href="http://docs.unity3d.com/Documentation/Components/SL-ShaderPrograms.html" target="_blank">http://docs.unity3d.com/Documentation/Components/SL-ShaderPrograms.html</a><br />
<a href="http://docs.unity3d.com/Documentation/Components/SL-RenderPipeline.html" target="_blank">http://docs.unity3d.com/Documentation/Components/SL-RenderPipeline.html</a><br />
<a href="http://docs.unity3d.com/Documentation/Components/Rendering-Tech.html" target="_blank">http://docs.unity3d.com/Documentation/Components/Rendering-Tech.html</a><br />
<a href="http://unity3d.com/unity/download/archive" target="_blank">http://unity3d.com/unity/download/archive</a></p>
<span id="Images_Used"><h1>Images Used</h1></span>
<p><a href="http://docs.unity3d.com/Documentation/Images/manual/Materials-1.jpg">http://docs.unity3d.com/Documentation/Images/manual/Materials-1.jpg</a></p>
<span id="Suggested_reading:"><h1>Suggested reading:</h1></span>
<p><a href="http://blogs.unity3d.com/2010/07/17/unity-3-technology-surface-shaders/" target="_blank">http://blogs.unity3d.com/2010/07/17/unity-3-technology-surface-shaders/</a></p>
<p><a href="http://http.developer.nvidia.com/CgTutorial/cg_tutorial_chapter01.html" target="_blank">http://http.developer.nvidia.com/CgTutorial/cg_tutorial_chapter01.html</a></p>
<span id="Download_Unity_Project"><h1>Download Unity Project</h1></span>
<p><a href="https://docs.google.com/open?id=0B0ND0J8HHfaXd1NUcUhmcmp2UlU">[UnityShaders.zip]</a></p>
]]></content:encoded>
			<wfw:commentRss>http://3dgep.com/?feed=rss2&#038;p=4622</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating Terrains with Unity</title>
		<link>http://3dgep.com/?p=4691</link>
		<comments>http://3dgep.com/?p=4691#comments</comments>
		<pubDate>Sat, 24 Nov 2012 12:26:33 +0000</pubDate>
		<dc:creator>Jeremiah van Oosten</dc:creator>
				<category><![CDATA[Unity]]></category>

		<guid isPermaLink="false">http://3dgep.com/?p=4691</guid>
		<description><![CDATA[In this article, I will introduce the reader to Terrains in Unity. I will describe the different terrain features that Unity offers and we will build a simple terrain that can be used in your game. Introduction In this article, &#8230; <a href="http://3dgep.com/?p=4691">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="attachment_4826" class="wp-caption alignleft" style="width: 160px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Terrains-in-Unity-Thumb.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/11/Terrains-in-Unity-Thumb-150x150.jpg" alt="Terrains in Unity" title="Terrains in Unity" width="150" height="150" class="size-thumbnail wp-image-4826" /></a><p class="wp-caption-text">Terrains in Unity</p></div>
<p>In this article, I will introduce the reader to Terrains in Unity. I will describe the different terrain features that Unity offers and we will build a simple terrain that can be used in your game.</p>
<p><span id="more-4691"></span></p>
<div style="clear: both;"><div class='toc wptoc'>
<h2>Table of Contents</h2>
<ol class='toc-odd level-1'>
	<li>
		<a href="#Introduction">Introduction</a>
	</li>
	<li>
		<a href="#Creating_a_Terrain">Creating a Terrain</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Terrain_Resolution">Terrain Resolution</a>
			</li>
		</ol>
	<li>
		<a href="#Terrain_Heightmap">Terrain Heightmap</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#RaiseLower_Height">Raise/Lower Height</a>
			</li>
			<li>
				<a href="#Paint_Height">Paint Height</a>
			</li>
			<li>
				<a href="#Smooth_Height">Smooth Height</a>
			</li>
			<li>
				<a href="#ImportExport_Heightmap">Import/Export Heightmap</a>
			</li>
		</ol>
	<li>
		<a href="#Terrain_Textures">Terrain Textures</a>
	</li>
	<li>
		<a href="#Trees">Trees</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Mass_Place_Trees">Mass Place Trees</a>
			</li>
			<li>
				<a href="#Creating_Custom_Trees">Creating Custom Trees</a>
			</li>
		</ol>
	<li>
		<a href="#Grass">Grass</a>
	</li>
	<li>
		<a href="#Detail_Meshes">Detail Meshes</a>
	</li>
	<li>
		<a href="#Terrain_Settings">Terrain Settings</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Base_Terrain">Base Terrain</a>
			</li>
			<li>
				<a href="#Tree__Detail_Objects">Tree & Detail Objects</a>
			</li>
			<li>
				<a href="#Wind_Settings">Wind Settings</a>
			</li>
		</ol>
	<li>
		<a href="#Lightmapping">Lightmapping</a>
	</li>
	<li>
		<a href="#Conclusion">Conclusion</a>
	</li>
	<li>
		<a href="#References">References</a>
	</li>
</ol>
</div>
<div class='wptoc-end'>&nbsp;</div></div>
<span id="Introduction"><h1>Introduction</h1></span>
<p>In this article, I will explain how to use the Terrain Engine in Unity.</p>
<p>I assume the reader has a basic understanding of Unity including creating a new Unity project and, asset management, and the basic GameObject-Component model. If not, then I would refer the reader to my previous article which provides an introduction to Unity here: <a href="http://3dgep.com/?p=3246" title="Introduction to Unity">http://3dgep.com/?p=3246</a>.</p>
<span id="Creating_a_Terrain"><h1>Creating a Terrain</h1></span>
<p>To create a new Terrain in your scene, select <strong>Terrain > Create Terrain</strong> from the main menu.</p>
<div id="attachment_4711" class="wp-caption alignnone" style="width: 634px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Create-Terrain.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Create-Terrain.png" alt="Unity - Create Terrain" title="Unity - Create Terrain" width="624" height="468" class="size-full wp-image-4711" /></a><p class="wp-caption-text">Unity &#8211; Create Terrain</p></div>
<p>This will add a new <strong>Terrain Asset</strong> in the Project view and add a GameObject in the scene with a <strong>Terrain (Script)</strong> component and a <strong>Terrain Collider</strong> component that references the new <strong>Terrain Asset</strong>.</p>
<div id="attachment_4716" class="wp-caption alignnone" style="width: 1032px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-New-Terrain.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-New-Terrain.png" alt="Unity - New Terrain" title="Unity - New Terrain" width="1022" height="765" class="size-full wp-image-4716" /></a><p class="wp-caption-text">Unity &#8211; New Terrain</p></div>
<span id="Terrain_Resolution"><h2>Terrain Resolution</h2></span>
<p>If you want to change the properties of the currently selected terrain, you can choose <strong>Terrain > Set Resolution</strong> from the main menu.</p>
<div id="attachment_4719" class="wp-caption alignnone" style="width: 578px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Terrain-Resolution.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Terrain-Resolution.png" alt="Unity - Terrain Resolution" title="Unity - Terrain Resolution" width="568" height="281" class="size-full wp-image-4719" /></a><p class="wp-caption-text">Unity &#8211; Terrain Resolution</p></div>
<p>The <strong>Set Heightmap Resolution</strong> dialog box exposes the following properties:</p>
<ul>
<li><strong>Terrain Width</strong>: Allows you to specify the width (X-axis) of the terrain in world units.</li>
<li><strong>Terrain Height</strong>: Allows you to specify the maximum height (Y-axis) of the terrain in world units.</li>
<li><strong>Terrain Length</strong>: Allows you to specify the length (Z-axis) of the terrain in world units.</li>
<li><strong>Heightmap Resolution</strong>: The resolution of the terrain heightmap. The heightmap is always a square texture that has this value for both the width and height of the texture regardless of the size of the terrain.</li>
<li><strong>Detail Resolution</strong>: The resolution of the detail map that controls the grass and detail meshes. For best performance, you should keep this value as small as possible while still maintaining the desired amount of detail.</li>
<li><strong>Detail Resolution Per Patch</strong>: The detail texture is split into patches according to this parameter where each patch combines all of the detail (grass and detail meshes) into a single piece of geometry and a single texture.  For example a <strong>Detail Resolution</strong> map of 1024&#215;1024 will be split into 128&#215;128 detail patches if <strong>Detail Resolution Per Patch</strong> is set to 8.  Larger values for this parameter will produce less detail patches and thus less draw class to the GPU if a lot of terrain is visible. Smaller values will produce more patches which could potentially produce more draw calls (depending on how much of the terrain is visible).  If you have relatively flat terrain, I would suggest to set this value higher (64, or 128 for example) but if you have a mountainous terrain, I would suggest you keep this value smaller (8 or 16 for example).</li>
<li><strong>Control Texture Resolution</strong>: The resolution of the spat map that is used to layer the different textures that are painted onto the Terrain.</li>
<li><strong>Base Texture Resolution</strong>: The base texture is used in place of the splat map when the viewer is sufficiently far away.</li>
</ul>
<span id="Terrain_Heightmap"><h1>Terrain Heightmap</h1></span>
<p>The Terrain Heightmap is a 2-dimensional texture that is used to encode the height of each point on the terrain. The height values of the terrain are usually encoded in 8, or 16-bit floating point values in the range 0 to 1. A value of 0 in the heightmap indicates the lowest part of the terrain and a value of 1 in the heightmap indicates the highest part of the terrain.</p>
<div id="attachment_4729" class="wp-caption alignnone" style="width: 267px"><a href="http://3dgep.com/wp-content/uploads/2012/11/terrain257x257.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/terrain257x257.png" alt="Terrain Heightmap" title="Terrain Heightmap" width="257" height="257" class="size-full wp-image-4729" /></a><p class="wp-caption-text">Terrain Heightmap</p></div>
<p>The original terrain heightmap can be generated in an external tool such as <strong>Terragen</strong> (<a href="http://www.planetside.co.uk/" title="Terragen" target="_blank">http://www.planetside.co.uk/</a>) or using plug-ins purchased on the <strong>Asset Store</strong> directly in Unity.  You can also create your terrain heigtmap directly in Unity using the available heightmap tools.</p>
<div id="attachment_4731" class="wp-caption alignnone" style="width: 233px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Terrain-Tool.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Terrain-Tool.png" alt="Unity - Terrain Tool" title="Unity - Terrain Tool" width="223" height="22" class="size-full wp-image-4731" /></a><p class="wp-caption-text">Unity &#8211; Terrain Tool</p></div>
<p>The first three buttons on the <strong>Terrain Toolbar</strong> allow you to adjust the height of the terrain using the following tools:</p>
<ul>
<li><strong>Raise/Lower Height</strong>: The Raise/Lower tool is used to adjust the height of the terrain using a variety of brushes.</li>
<li><strong>Paint Height</strong>: The Paint Height tool allows you to flatten areas of the terrain to a specific height.</li>
<li><strong>Smooth Height</strong>: The smooth height tool allows you to smooth rough edges of the terrain.</li>
</ul>
<span id="RaiseLower_Height"><h2>Raise/Lower Height</h2></span>
<p>As the name suggests, the <strong>Raise/Lower Height</strong> tool allows you to raise and lower the height of the terrain.  The terrain can be raised to the maximum (1.0) height and it can be lowered to the minimum height (0.0). You cannot lower the terrain below the lowest possible value.</p>
<div id="attachment_4734" class="wp-caption alignnone" style="width: 286px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Raise_Lower-Height.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Raise_Lower-Height.png" alt="Unity - Raise/Lower Height" title="Unity - Raise/Lower Height" width="276" height="451" class="size-full wp-image-4734" /></a><p class="wp-caption-text">Unity &#8211; Raise/Lower Height</p></div>
<p>Clicking on the terrain will raise the terrain incrementally. Holding <strong>Shift</strong> while clicking will cause the terrain to lower incrementally.  Keeping the mouse button held down while moving the mouse will allow you to raise and lower the terrain continuously.</p>
<div id="attachment_4749" class="wp-caption alignnone" style="width: 899px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Raise_Lower-Terrain-Tool.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Raise_Lower-Terrain-Tool.png" alt="Unity - Raise/Lower Terrain Tool" title="Unity - Raise/Lower Terrain Tool" width="889" height="591" class="size-full wp-image-4749" /></a><p class="wp-caption-text">Unity &#8211; Raise/Lower Terrain Tool</p></div>
<p>The Raise/Lower Height brush has the following properties:</p>
<ul>
<li><strong>Brush Size</strong>: This slider allows you to select the size of the brush in terrain heightmap resolution units.  The minimum value being 1 terrain heightmap pixel and the maximum value being 100 terrain heightmap pixels.</li>
<li><strong>Brush Opacity</strong>: The brush opacity determines the intensity of the change that occurs.  This slider property can have a minimum value of 0 which will cause no change to occur and a maximum value of 100 which will cause the terrain to be raised/lowered a full increment.
</li>
</ul>
<span id="Paint_Height"><h2>Paint Height</h2></span>
<p>The <strong>Paint Height</strong> terrain tool will allow you to flatten certain areas of the terrain to a specific height.</p>
<div id="attachment_4751" class="wp-caption alignnone" style="width: 899px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Paint-Height-Terrain-Tool.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Paint-Height-Terrain-Tool.png" alt="Unity - Paint Height Terrain Tool" title="Unity - Paint Height Terrain Tool" width="889" height="591" class="size-full wp-image-4751" /></a><p class="wp-caption-text">Unity &#8211; Paint Height Terrain Tool</p></div>
<p>This is useful for creating plateaus and shelves on your terrain.</p>
<p>The Paint Height terrain tool has the following properties:</p>
<ul>
<li><strong>Brush Size</strong>: This slider allows you to select the radius of the brush in terrain heightmap resolution units.  The minimum value being 1 terrain heightmap pixel and the maximum value being 100 terrain heightmap pixels.</li>
<li><strong>Brush Opacity</strong>: The brush opacity determines the intensity of the change that occurs.  This slider property can have a minimum value of 0 which will cause no change to occur and a maximum value of 100 which will cause the terrain to be adjusted a full increment.
</li>
<li><strong>Height</strong>: This value determines the desired height to set the terrain to.  This value is measured in world-units. The minimum value is 0 and the maximum value is the value of the <strong>Terrain Height</strong> parameter specified in the <strong>Terrain Heigtmap Resolution</strong> dialog box.  You can adjust this slider value manually, or you can <strong>Shift-Click</strong> on a part of the terrain to set this property to the height of the terrain at the clicked point.</li>
</ul>
<span id="Smooth_Height"><h2>Smooth Height</h2></span>
<p>After adjusting the height of the terrain several times using the <strong>Raise/Lower</strong> and <strong>Paint Height</strong> tools, the terrain can become quite jagged.  The <strong>Smooth Height</strong> terrain tool can be used to smooth-out these apparent jaggies to create a more natural, smooth terrain.  This is equivalent to the erosion that occurs naturally after thousands of years of exposure to weather conditions.</p>
<p>The image below shows an example of jaggies that occur after manipulating the terrain.</p>
<div id="attachment_4753" class="wp-caption alignnone" style="width: 899px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Terrain-Jaggies.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Terrain-Jaggies.jpg" alt="Unity - Terrain Jaggies" title="Unity - Terrain Jaggies" width="889" height="591" class="size-full wp-image-4753" /></a><p class="wp-caption-text">Unity &#8211; Terrain Jaggies</p></div>
<p>After smoothing:</p>
<div id="attachment_4754" class="wp-caption alignnone" style="width: 899px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Smooth-Terrain.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Smooth-Terrain.jpg" alt="Unity - Smooth Terrain" title="Unity - Smooth Terrain" width="889" height="591" class="size-full wp-image-4754" /></a><p class="wp-caption-text">Unity &#8211; Smooth Terrain</p></div>
<p>The Smooth Height terrain tool has the following properties:</p>
<ul>
<li><strong>Brush Size</strong>: This slider allows you to select the radius of the brush in terrain heightmap resolution units.  The minimum value being 1 terrain heightmap pixel and the maximum value being 100 terrain heightmap pixels.</li>
<li><strong>Brush Opacity</strong>: The brush opacity determines the intensity of the change that occurs.  This slider property can have a minimum value of 0 which will cause no change to occur and a maximum value of 100 which will cause the terrain to apply the maximum amount of smoothing.
</li>
</ul>
<span id="ImportExport_Heightmap"><h2>Import/Export Heightmap</h2></span>
<p>After you have created your prefect heightmap, you may want to export it for use in another project or to be used in an external program to be fine-tuned.  Or, you may want to import a heightmap that was created with an external tool such as Bryce, Terragen, or Photoshop.</p>
<p>To export your heightmap from Unity, select <strong>Terrain > Export Heightmap &#8211; Raw&#8230;</strong> from the main menu.</p>
<div id="attachment_4756" class="wp-caption alignnone" style="width: 810px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Export-Heightmap.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Export-Heightmap.jpg" alt="Unity - Export Heightmap" title="Unity - Export Heightmap" width="800" height="600" class="size-full wp-image-4756" /></a><p class="wp-caption-text">Unity &#8211; Export Heightmap</p></div>
<p>The Export Heightmap dialog box should appear.</p>
<div id="attachment_4757" class="wp-caption alignnone" style="width: 378px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Terrain-Export-Heightmap-Dialog.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Terrain-Export-Heightmap-Dialog.png" alt="Terrain - Export Heightmap Dialog" title="Terrain - Export Heightmap Dialog" width="368" height="304" class="size-full wp-image-4757" /></a><p class="wp-caption-text">Terrain &#8211; Export Heightmap Dialog</p></div>
<p>In most cases, the default settings should be sufficient.  Click the &#8220;<strong>Export</strong>&#8221; button to export your heightmap to a Raw file.</p>
<p>Because the Raw file format does not encode the pixel format or the dimensions of the texture in the file itself, it is generally a good idea to save the file with this information in the filename.  For example, a <strong>16-bit</strong> heigtmap texture of size <strong>257&#215;257</strong> pixels should be saved with the name:</p>
<pre>
terrain_257x257_16-bit.raw
</pre>
<p>This way, if you want to use this texture in another program, you already know the size of the texture and the pixel format.</p>
<p>You can then use your texture in a program such as Bryce, Terragen, or Photoshop to fine-tune the heightmap.</p>
<p>For example, if you open a raw file in Photoshop, you will get the following dialog box:</p>
<div id="attachment_4759" class="wp-caption alignnone" style="width: 321px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Photoshop-Raw-File-Options.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Photoshop-Raw-File-Options.png" alt="Photoshop - Raw File Options" title="Photoshop - Raw File Options" width="311" height="418" class="size-full wp-image-4759" /></a><p class="wp-caption-text">Photoshop &#8211; Raw File Options</p></div>
<p>If you specify the correct settings according to how you exported the Raw file in Unity, you should see the heightmap of your terrain in Photoshop.</p>
<div id="attachment_4760" class="wp-caption alignnone" style="width: 897px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Phtoshop-Edit-Raw-File.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Phtoshop-Edit-Raw-File.png" alt="Phtoshop - Edit Raw File" title="Phtoshop - Edit Raw File" width="887" height="620" class="size-full wp-image-4760" /></a><p class="wp-caption-text">Phtoshop &#8211; Edit Raw File</p></div>
<p>After you make the necessary adjustments to the terrain in Photoshop you can import the modified terrain file into Unity using the <strong>Terrain > Import Heightmap &#8211; RAW&#8230;</strong> command from the main menu in Unity.</p>
<span id="Terrain_Textures"><h1>Terrain Textures</h1></span>
<p>Textures can be painted onto the terrain using the Paint Texture tool.</p>
<div id="attachment_4763" class="wp-caption alignnone" style="width: 286px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Paint-Texture.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Paint-Texture.png" alt="Unity - Paint Texture" title="Unity - Paint Texture" width="276" height="535" class="size-full wp-image-4763" /></a><p class="wp-caption-text">Unity &#8211; Paint Texture</p></div>
<p>Before you can paint any textures to the terrain, you must first add at least one texture to the terrain.  To get started quickly, Unity provides suitable terrain assets in the <strong>Standard Packages</strong> that comes with Unity.  To import the <strong>Terrain Assets</strong>, select <strong>Assets > Import Package > Terrain Assets</strong> from the main menu.</p>
<div id="attachment_4766" class="wp-caption alignnone" style="width: 636px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Import-Terrain-Assets.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Import-Terrain-Assets.png" alt="Unity - Import Terrain Assets" title="Unity - Import Terrain Assets" width="626" height="384" class="size-full wp-image-4766" /></a><p class="wp-caption-text">Unity &#8211; Import Terrain Assets</p></div>
<p>Click the <strong>Import</strong> button to import these assets into your current project.</p>
<p>With the <strong>Paint Texture</strong> tool selected in the <strong>Inspector</strong> click the <strong>Edit Textures&#8230;</strong> button and select <strong>Add Texture</strong> from the popup that appears.</p>
<div id="attachment_4769" class="wp-caption alignnone" style="width: 284px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Add-Terrain-Texture.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Add-Terrain-Texture.png" alt="Unity - Add Terrain Texture" title="Unity - Add Terrain Texture" width="274" height="533" class="size-full wp-image-4769" /></a><p class="wp-caption-text">Unity &#8211; Add Terrain Texture</p></div>
<p>The <strong>Add Terrain Texture</strong> dialog box should appear.</p>
<div id="attachment_4770" class="wp-caption alignnone" style="width: 402px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Add-Texture.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Add-Texture.png" alt="Unity - Add Texture" title="Unity - Add Texture" width="392" height="240" class="size-full wp-image-4770" /></a><p class="wp-caption-text">Unity &#8211; Add Texture</p></div>
<p>The <strong>Add Terrain Texture</strong> dialog has the following properties.</p>
<ul>
<li><strong>Splat</strong>: The texture to apply to this slot in the terrain.</li>
<li><strong>Tile Size</strong>: How large each tile of the texture is applied to the terrain.  Larger tiles means the texture will have less tiles across the terrain in each direction. Smaller tiles will mean the texture will be repeated more times across the terrain in each direction.</li>
<li><strong>Tile Offset</strong>: Adjusting this parameter will shift the texture in the terrain. This is useful if you want to blend multiple layers with the same texture to break the repetition that occurs when using a single texture.</li>
</ul>
<p>Click the target button on the <strong>Splat</strong> parameter and select a texture to apply to the terrain.</p>
<div id="attachment_4771" class="wp-caption alignnone" style="width: 363px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Select-Texture.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Select-Texture.png" alt="Unity - Select Texture" title="Unity - Select Texture" width="353" height="420" class="size-full wp-image-4771" /></a><p class="wp-caption-text">Unity &#8211; Select Texture</p></div>
<p>After you apply the texture to the terrain, you should see the entire terrain covered in that texture.</p>
<div id="attachment_4773" class="wp-caption alignnone" style="width: 957px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Textured-Terrain.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Textured-Terrain.png" alt="Unity - Textured Terrain" title="Unity - Textured Terrain" width="947" height="627" class="size-full wp-image-4773" /></a><p class="wp-caption-text">Unity &#8211; Textured Terrain</p></div>
<p>The Paint Texture terrain tool has the following properties:</p>
<ul>
<li><strong>Textures</strong>: The Textures property shows the different textures that are assigned to the various texture slots of the terrain.  You can have a maximum of 255 textures assigned to the terrain.</li>
<li><strong>Brush Size</strong>: The radius of the <strong>Paint Texture</strong> brush measured in pixels of the <strong>Control Texture</strong> resolution.</li>
<li><strong>Opacity</strong>: The intensity that the selected texture will be applied to the terrain. This parameter is measured as a percentage from 0 to 100.</li>
<li><strong>Target Strength</strong>: The <strong>Target Strength</strong> parameter can be used to cap the intensity of the currently selected texture.  This value is measured as a ratio of the amount of texture that will replace the texture under it. If you don&#8217;t want to apply more than 50% opacity of the selected texture to the terrain, then you should set this value to 0.5.</li>
</ul>
<p>Before you can blend textures on the terrain, you must have at least 2 textures in the terrain&#8217;s texture list.  Add a few more textures to your terrain and use the <strong>Paint Texture</strong> tool to fancy-up your terrain. The currently selected texture will have a blue outline in the <strong>Inspector</strong>.</p>
<div id="attachment_4776" class="wp-caption alignnone" style="width: 907px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Textured-Terrain-2.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Textured-Terrain-2.jpg" alt="Unity - Textured Terrain (2)" title="Unity - Textured Terrain (2)" width="897" height="611" class="size-full wp-image-4776" /></a><p class="wp-caption-text">Unity &#8211; Textured Terrain (2)</p></div>
<div class="my-note">
As far as I know, there is no options or settings to automatically paint the textures of the terrain based on the height and slope of the terrain.  Most likely there is a (paid) plug-in that will do that for you automatically.
</div>
<p>Now that we have some interesting textures applied to the terrain, it&#8217;s time to add some detail.</p>
<span id="Trees"><h1>Trees</h1></span>
<p>Trees can be painted onto the terrain using the <strong>Place Tree</strong> tool in the inspector.</p>
<div id="attachment_4780" class="wp-caption alignnone" style="width: 316px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Place-Trees-Tool.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Place-Trees-Tool.png" alt="Unity - Place Trees Tool" title="Unity - Place Trees Tool" width="306" height="517" class="size-full wp-image-4780" /></a><p class="wp-caption-text">Unity &#8211; Place Trees Tool</p></div>
<p>Just like the <strong>Paint Texture</strong> tool, the <strong>Place Tree</strong> tool requires at least one tree to be added to the terrain.</p>
<p>Click the <strong>Edit Trees&#8230;</strong> button and select <strong>Add Tree</strong> from the pop-up menu that appears.</p>
<div id="attachment_4781" class="wp-caption alignnone" style="width: 366px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Add-Tree-Dialog.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Add-Tree-Dialog.png" alt="Unity - Add Tree Dialog" title="Unity - Add Tree Dialog" width="356" height="300" class="size-full wp-image-4781" /></a><p class="wp-caption-text">Unity &#8211; Add Tree Dialog</p></div>
<p>The Add Tree dialog provides the following properties:</p>
<ul>
<li><strong>Tree</strong>: The tree model to use for this slot in the terrain&#8217;s tree list.</li>
<li><strong>Bend Factor</strong>: The the amount of bending that will be applied to the trees when they are effected by wind.</li>
</ul>
<p>Select the target icon next to the Tree property and select a tree from the dialog that appears.</p>
<div id="attachment_4784" class="wp-caption alignnone" style="width: 363px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Select-Tree.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Select-Tree.png" alt="Unity - Select Tree" title="Unity - Select Tree" width="353" height="420" class="size-full wp-image-4784" /></a><p class="wp-caption-text">Unity &#8211; Select Tree</p></div>
<p>Click the <strong>Add</strong> button to add that tree to the tree list for the terrain.</p>
<div id="attachment_4785" class="wp-caption alignnone" style="width: 286px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Tree-Inspector.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Tree-Inspector.png" alt="Unity - Tree Inspector" title="Unity - Tree Inspector" width="276" height="697" class="size-full wp-image-4785" /></a><p class="wp-caption-text">Unity &#8211; Tree Inspector</p></div>
<p>The Place Trees tool has the following properties:</p>
<ul>
<li><strong>Trees</strong>: The list of trees assigned to the different slots of the terrain.</li>
<li><strong>Brush Size</strong>: The radius of the brush in world unit.</li>
<li><strong>Tree Density</strong>: How many trees will be placed when the terrain is painted.</li>
<li><strong>Color Variation</strong>: The amount of random shading that will be applied to the trees when they are painted.</li>
<li><strong>Tree Height</strong>: The amount of scaling to apply to the painted trees. A value of 100 will paint the trees with a scale of 1 and a value of 200 will double the height of the trees.
<div id="attachment_4786" class="wp-caption alignnone" style="width: 1033px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Tree-Heights.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Tree-Heights.png" alt="Unity - Tree Heights" title="Unity - Tree Heights" width="1023" height="588" class="size-full wp-image-4786" /></a><p class="wp-caption-text">Unity &#8211; Tree Heights</p></div>
<p>The image shows the trees on the left are painted with a height of 50, the trees in the middle are painted with a height of 100 and the trees on the right are painted with a height of 200.</p>
<ul>
<li><strong>Variation</strong>: The amount of random variation to apply to the tree heights.</li>
</ul>
</li>
<li><strong>Tree Width</strong>: The amount of scaling to apply to the width and depth of the tree.
<ul>
<li><strong>Variation</strong>: The amount of random variation to apply to width of the tree.</li>
</ul>
</ul>
<span id="Mass_Place_Trees"><h2>Mass Place Trees</h2></span>
<p>You can have Unity automatically place trees for you on the terrain by using the <strong>Mass Place Trees</strong> option in the <strong>Terrain</strong> menu.</p>
<div id="attachment_4789" class="wp-caption alignnone" style="width: 361px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Mass-Place-Trees.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Mass-Place-Trees.png" alt="Unity - Mass Place Trees" title="Unity - Mass Place Trees" width="351" height="159" class="size-full wp-image-4789" /></a><p class="wp-caption-text">Unity &#8211; Mass Place Trees</p></div>
<p>Select the number of trees that you would like to place and press the &#8220;<strong>Place</strong>&#8221; button to randomly place that number of trees on your terrain.  Doing this will replace any trees that you have already placed on the terrain.</p>
<div id="attachment_4790" class="wp-caption alignnone" style="width: 903px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Mass-Place-Trees-2.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Mass-Place-Trees-2.png" alt="Unity - Mass Place Trees (2)" title="Unity - Mass Place Trees (2)" width="893" height="543" class="size-full wp-image-4790" /></a><p class="wp-caption-text">Unity &#8211; Mass Place Trees (2)</p></div>
<p>Unity will place the trees on relatively flat areas of your terrain.</p>
<span id="Creating_Custom_Trees"><h2>Creating Custom Trees</h2></span>
<p>Unity provides the <strong>Tree Creator</strong> tool that allows you to create your own custom trees directly in the Unity editor.  To create a custom tree in Unity, create a new <strong>Tree</strong> GameObject by selecting <strong>GameObject > Create Other > Tree</strong> from the main menu.</p>
<div id="attachment_4792" class="wp-caption alignnone" style="width: 1281px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Tree-Creator.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Tree-Creator.jpg" alt="Unity - Tree Creator" title="Unity - Tree Creator" width="1271" height="755" class="size-full wp-image-4792" /></a><p class="wp-caption-text">Unity &#8211; Tree Creator</p></div>
<p>You can also import the <strong>Tree Creator</strong> package from the <strong>Standard Assets</strong> that ship with Unity (select <strong>Assets > Import Package > Tree Creator</strong> from the main menu).  This package gives you access to some textures that can be used to create your own trees in Unity.  The image above shows the <strong>Big Tree</strong> tree asset that has been created with the <strong>Tree Creator</strong> tool.</p>
<p>To learn more about how to use the <strong>Tree Creator</strong> tool to build custom trees in Unity, please refer to the online documentation on the Unity website:<br />
<a href="http://docs.unity3d.com/Documentation/Components/class-Tree.html" title="Unity - Tree Creator" target="_blank">http://docs.unity3d.com/Documentation/Components/class-Tree.html</a></p>
<span id="Grass"><h1>Grass</h1></span>
<p>To add grass to the terrain, select the <strong>Paint Details</strong> tool in the <strong>Inspector</strong>.</p>
<div id="attachment_4797" class="wp-caption alignnone" style="width: 286px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Paint-Details-Tool.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Paint-Details-Tool.png" alt="Unity - Paint Details Tool" title="Unity - Paint Details Tool" width="276" height="547" class="size-full wp-image-4797" /></a><p class="wp-caption-text">Unity &#8211; Paint Details Tool</p></div>
<p>Similar to the <strong>Paint Texture</strong> and the <strong>Place Trees</strong> tools, the <strong>Paint Details</strong> tool needs to have some detail objects to be defined.</p>
<p>Click the <strong>Edit Details&#8230;</strong> button and select <strong>Add Grass Texture</strong> in the pop-up menu that appears.</p>
<div id="attachment_4798" class="wp-caption alignnone" style="width: 316px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Add-Grass-Texture.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Add-Grass-Texture.png" alt="Unity - Add Grass Texture" title="Unity - Add Grass Texture" width="306" height="286" class="size-full wp-image-4798" /></a><p class="wp-caption-text">Unity &#8211; Add Grass Texture</p></div>
<p>The Add Grass Texture dialog has the following properties:</p>
<ul>
<li><strong>Detail Texture</strong>: The texture to be used for the grass.</li>
<li><strong>Min Width</strong>: Minimum width of each grass section in world units.</li>
<li><strong>Max Width</strong>: Maximum width of each grass section in world units.</li>
<li><strong>Min Height</strong>: Minimum height of each grass section in world units.</li>
<li><strong>Max Height</strong>: Maximum height of each grass section in world units.</li>
<li><strong>Noise Spread</strong>: The size of noise-generated clusters of grass. Lower numbers mean less noise.</li>
<li><strong>Healthy Color</strong>: The color of healthy grass, prominent in the center of <strong>Noise Spread</strong> clusters.</li>
<li><strong>Dry Color</strong>: Color of dry grass, prominent on the outer edges of <strong>Noise Spread</strong> clusters.</li>
<li><strong>Billboard</strong>: If checked, this grass will always be rotated to face the current <strong>Camera</strong>.</li>
</ul>
<p>Click the target icon next to the <strong>Detail Texture</strong> property and select a grass texture in the <strong>Select Texture2D</strong> dialog that appears.</p>
<div id="attachment_4800" class="wp-caption alignnone" style="width: 363px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Select-Grass-Texture.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Select-Grass-Texture.png" alt="Unity - Select Grass Texture" title="Unity - Select Grass Texture" width="353" height="420" class="size-full wp-image-4800" /></a><p class="wp-caption-text">Unity &#8211; Select Grass Texture</p></div>
<p>The <strong>Terrain Assets</strong> in the <strong>Standard Packages</strong> contains a couple grass textures that can be used on your terrain.  Add the grass textures to your terrain and paint some areas with grass.</p>
<div id="attachment_4802" class="wp-caption alignnone" style="width: 987px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Grass-Detail-Textures.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Grass-Detail-Textures.png" alt="Unity - Grass Detail Textures" title="Unity - Grass Detail Textures" width="977" height="655" class="size-full wp-image-4802" /></a><p class="wp-caption-text">Unity &#8211; Grass Detail Textures</p></div>
<span id="Detail_Meshes"><h1>Detail Meshes</h1></span>
<p>Similar to grass, detail meshes are added to the terrain using the <strong>Paint Details</strong> tool.</p>
<div id="attachment_4797" class="wp-caption alignnone" style="width: 286px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Paint-Details-Tool.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Paint-Details-Tool.png" alt="Unity - Paint Details Tool" title="Unity - Paint Details Tool" width="276" height="547" class="size-full wp-image-4797" /></a><p class="wp-caption-text">Unity &#8211; Paint Details Tool</p></div>
<p>To add a detail mesh to the terrain, click the <strong>Edit Details&#8230;</strong> button in the inspector and select <strong>Add Detail Mesh</strong> from the pop-up menu that appears.</p>
<div id="attachment_4808" class="wp-caption alignnone" style="width: 335px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Add-Detail-Mesh.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Add-Detail-Mesh.png" alt="Unity - Add Detail Mesh" title="Unity - Add Detail Mesh" width="325" height="337" class="size-full wp-image-4808" /></a><p class="wp-caption-text">Unity &#8211; Add Detail Mesh</p></div>
<p>The <strong>Add Detail Mesh</strong> dialog has the following properties:</p>
<ul>
<li><strong>Detail</strong>: The mesh to be used for the detail.</li>
<li><strong>Noise Spread</strong>: The size of noise-generated clusters of the Detail. Lower numbers mean less noise.</li>
<li><strong>Random Width</strong>: Limit for the amount of width variance between all detail objects.</li>
<li><strong>Random Height</strong>: Limit for the amount of height variance between all detail objects.</li>
<li><strong>Healthy Color</strong>: Color of healthy detail objects, prominent in the center of Noise Spread clusters.</li>
<li><strong>Dry Color</strong>: Color of dry detail objects, prominent on the outer edges of Noise Spread clusters.</li>
<li><strong>Render Mode</strong>: Select whether this type of detail object will be lit using Grass lighting or normal Vertex lighting. Detail objects like rocks should use <strong>VertexLit</strong>.  Detail mesh that should be effected by wind (such as bushes) should be set to <strong>Grass</strong>.</li>
</ul>
<p>The <strong>Terrain Assets</strong> in the Standard Assets package does not include any meshes that can be used as detail meshes for the terrain, but you can download the <strong>Terrain Assets</strong> package that is provided on the Unity website contains some bushes and rocks that can be used to add some detail to your terrain.  You can download the Terrain Assets package here:<br />
<a href="http://unity3d.com/support/resources/assets/terrain-assets" title="Unity - Terrain Assets" target="_blank">http://unity3d.com/support/resources/assets/terrain-assets</a></p>
<p>Add some detail meshes to your terrain.</p>
<div id="attachment_4811" class="wp-caption alignnone" style="width: 1043px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Detail-Meshes.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Detail-Meshes.jpg" alt="Unity - Detail Meshes" title="Unity - Detail Meshes" width="1033" height="749" class="size-full wp-image-4811" /></a><p class="wp-caption-text">Unity &#8211; Detail Meshes</p></div>
<p>If you make changes to detail meshes outside of Unity, the meshes are not automatically updated in your terrain. To tell unity to apply the changes you made to a detail mesh, select <strong>Terrain > Refresh Tree and Detail Prototypes</strong> from the main menu.</p>
<span id="Terrain_Settings"><h1>Terrain Settings</h1></span>
<p>The last button on the Terrain toolbar is the <strong>Terrain Settings</strong>.</p>
<div id="attachment_4818" class="wp-caption alignnone" style="width: 286px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Terrain-Setttings.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Terrain-Setttings.png" alt="Unity - Terrain Setttings" title="Unity - Terrain Setttings" width="276" height="589" class="size-full wp-image-4818" /></a><p class="wp-caption-text">Unity &#8211; Terrain Setttings</p></div>
<p>The properties of the <strong>Terrain Settings</strong> are split into three categories; <strong>Base Terrain</strong>, <strong>Tree &#038; Detail Objects</strong>, and <strong>Wind Settings</strong>.</p>
<span id="Base_Terrain"><h2>Base Terrain</h2></span>
<p>The <strong>Base Terrain</strong> settings affect the terrain mesh itself.</p>
<ul>
<li><strong>Pixel Error</strong>: This property controls the amount of allowable errors in the rendering of the Terrain geometry.  Parts of the terrain that are far away from the viewer use less vertices to render. As the viewer approaches the terrain, the terrain will refine to a more detailed mesh.  This is a rendering optimization.  The <strong>Pixel Error</strong> controls how much error can occur then the terrain is far away.  Higher values can result in better performance but more error.
<div id="attachment_4819" class="wp-caption alignnone" style="width: 861px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Pixel-Error.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Pixel-Error.jpg" alt="Unity - Pixel Error" title="Unity - Pixel Error" width="851" height="672" class="size-full wp-image-4819" /></a><p class="wp-caption-text">Unity &#8211; Pixel Error</p></div>
</li>
<li><strong>Base Map Dist.</strong>: The distance that Terrain textures will be displayed in high-resolution. After this distance, a low-resolution composite texture will be displayed.</li>
<li><strong>Cast Shadows</strong>: Should the terrain cast shadows?</li>
</ul>
<span id="Tree_038_Detail_Objects"><h2>Tree &#038; Detail Objects</h2></span>
<p>The <strong>Tree &#038; Detail Objects</strong> settings effect the rendering of the Trees, detail grass, and detail meshes.</p>
<ul>
<li><strong>Draw</strong>: Used to toggle the rendering of trees, grass, and detail meshes.</li>
<li><strong>Detail Distance</strong>: The distance from the camera that details will stop being rendered. The higher this value is, the farther away details will be visible. Raising this value could have a negative impact on rendering performance.</li>
<li><strong>Tree Distance</strong>: The distance from the camera that trees will stop being rendered. The higher this value is, the farther away trees will be visible.</li>
<li><strong>Billboard Start</strong>: The distance from the camera that trees will start appearing as <strong>Billboards</strong> instead of <strong>Meshes</strong>.</li>
<li><strong>Fade Length</strong>: The total distance delta that trees will use to transition from <strong>Billboard</strong> orientation to <strong>Mesh</strong> orientation.</li>
<li><strong>Max Mesh Trees</strong>: The maximum number of trees that will be drawn as Meshes.</li>
</ul>
<span id="Wind_Settings"><h2>Wind Settings</h2></span>
<p>The <strong>Wind Settings</strong> control how wind is simulated over the trees and grass on the terrain.</p>
<ul>
<li><strong>Speed</strong>: The speed that wind blows through grass.  Setting this value to 0 will top the wind from blowing, but the grass may appear bent in some areas.</li>
<li><strong>Size</strong>: The areas of grass that are affected by wind all at once.</li>
<li><strong>Bending</strong>: The amount that grass will bend due to wind.  Setting this value to 0 will prevent the grass from bending.  Setting this value too high may cause the grass to bend too much and will produce unnatural results.</li>
<li><strong>Grass Tint</strong>: As the wind blows over the grass, at tint can be applied to the grass and detail meshes. This gives the wind effect a bit more realism but this color should be subtle otherwise it will look unnatural.</li>
</ul>
<span id="Lightmapping"><h1>Lightmapping</h1></span>
<p>For better performance, terrains can be lightmapped just like any other static object in the scene. For terrains to be considered for lightmpping, they must be marked as <strong>Lightmap Static</strong> (by default, this should already be the case for terrains).</p>
<p>Lightmapping was covered in a previous article titled <a href="http://3dgep.com/?p=3856#Create_the_Lightmap" title="Rendering and Special Effects in Unity">Rendering and Special Effects in Unity</a>.</p>
<span id="Conclusion"><h1>Conclusion</h1></span>
<p>Unity provides a very powerful terrain engine with a lot of features such as grass, trees, and detail meshes.  But even with all of these features, it is very difficult to get exactly the result you want.  You must take care not to create too much detail near where the player can walk because colliders for detail meshes need to be created by hand.</p>
<p>But with enough skill and effort, it is possible to create very appealing terrains in a short time.</p>
<span id="References"><h1>References</h1></span>
<p>Unity Terrain Engine Guide (<a href="http://docs.unity3d.com/Documentation/Components/script-Terrain.html" title="Terrain Engine Guide" target="_blank">http://docs.unity3d.com/Documentation/Components/script-Terrain.html</a>)</p>
]]></content:encoded>
			<wfw:commentRss>http://3dgep.com/?feed=rss2&#038;p=4691</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Shuriken Particle Effects in Unity 3.5</title>
		<link>http://3dgep.com/?p=4313</link>
		<comments>http://3dgep.com/?p=4313#comments</comments>
		<pubDate>Mon, 12 Nov 2012 21:41:48 +0000</pubDate>
		<dc:creator>Jeremiah van Oosten</dc:creator>
				<category><![CDATA[Unity]]></category>
		<category><![CDATA[Effects]]></category>
		<category><![CDATA[Environment Effects]]></category>
		<category><![CDATA[Explosions]]></category>
		<category><![CDATA[Fire]]></category>
		<category><![CDATA[Flare]]></category>
		<category><![CDATA[Particle System]]></category>
		<category><![CDATA[Particles]]></category>
		<category><![CDATA[Rain]]></category>
		<category><![CDATA[Snow]]></category>
		<category><![CDATA[Sparks]]></category>
		<category><![CDATA[Water]]></category>

		<guid isPermaLink="false">http://3dgep.com/?p=4313</guid>
		<description><![CDATA[In this article I will introduce the Shuriken Particle System in Unity 3.5 <a href="http://3dgep.com/?p=4313">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="attachment_4569" class="wp-caption alignleft" style="width: 160px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particles-thumb.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particles-thumb.png" alt="Unity Particles" title="Unity Particles" width="150" height="150" class="size-full wp-image-4569" /></a><p class="wp-caption-text">Unity Particles</p></div>
<p>In this article I will introduce the Shuriken Particle System that was added to Unity in version 3.5.</p>
<p><span id="more-4313"></span></p>
<div style="clear: both;"><div class='toc wptoc'>
<h2>Table of Contents</h2>
<ol class='toc-odd level-1'>
	<li>
		<a href="#Introduction">Introduction</a>
	</li>
	<li>
		<a href="#Particle_System">Particle System</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Particle_System_GameObject">Particle System GameObject</a>
			</li>
			<li>
				<a href="#Particle_System_Component">Particle System Component</a>
			</li>
			<li>
				<a href="#Particle_System_Properties">Particle System Properties</a>
			</li>
			<li>
				<a href="#Preview_Panel">Preview Panel</a>
			</li>
		</ol>
	<li>
		<a href="#Particle_Effect_View">Particle Effect View</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Toolbar">Toolbar</a>
				<ol class='toc-odd level-3'>
					<li>
						<a href="#Preview_Controls">Preview Controls</a>
					</li>
					<li>
						<a href="#Show_AllSelected">Show All/Selected</a>
					</li>
					<li>
						<a href="#Resimulate">Resimulate</a>
					</li>
					<li>
						<a href="#Wireframe">Wireframe</a>
					</li>
					<li>
						<a href="#Layout">Layout</a>
					</li>
					<li>
						<a href="#Lock_Selected">Lock Selected</a>
					</li>
				</ol>
			<li>
				<a href="#Curve_Editor">Curve Editor</a>
			</li>
			<li>
				<a href="#Numeric_Properties">Numeric Properties</a>
				<ol class='toc-odd level-3'>
					<li>
						<a href="#Constant">Constant</a>
					</li>
					<li>
						<a href="#Curve">Curve</a>
					</li>
					<li>
						<a href="#Random_Between_Two_Constants">Random Between Two Constants</a>
					</li>
					<li>
						<a href="#Random_Between_Two_Curves">Random Between Two Curves</a>
					</li>
				</ol>
			<li>
				<a href="#Color_Properties">Color Properties</a>
				<ol class='toc-odd level-3'>
					<li>
						<a href="#Color">Color</a>
					</li>
					<li>
						<a href="#Gradient">Gradient</a>
					</li>
					<li>
						<a href="#Random_Between_Two_Colors">Random Between Two Colors</a>
					</li>
					<li>
						<a href="#Random_Between_Two_Gradients">Random Between Two Gradients</a>
					</li>
				</ol>
</ol>
			<li>
				<a href="#Particle_System_Modules">Particle System Modules</a>
				<ol class='toc-even level-2'>
					<li>
						<a href="#Initial_Module">Initial Module</a>
					</li>
					<li>
						<a href="#Emission_Module">Emission Module</a>
					</li>
					<li>
						<a href="#Shape_Module">Shape Module</a>
						<ol class='toc-odd level-3'>
							<li>
								<a href="#Sphere">Sphere</a>
							</li>
							<li>
								<a href="#HemiSphere">HemiSphere</a>
							</li>
							<li>
								<a href="#Cone">Cone</a>
							</li>
							<li>
								<a href="#Box">Box</a>
							</li>
							<li>
								<a href="#Mesh">Mesh</a>
							</li>
						</ol>
					<li>
						<a href="#Velocity_over_Lifetime_Module">Velocity over Lifetime Module</a>
					</li>
					<li>
						<a href="#Limit_Velocity_over_Lifetime_Module">Limit Velocity over Lifetime Module</a>
					</li>
					<li>
						<a href="#Force_over_Lifetime_Module">Force over Lifetime Module</a>
					</li>
					<li>
						<a href="#Color_over_Lifetime_Module">Color over Lifetime Module</a>
					</li>
					<li>
						<a href="#Color_by_Speed_Module">Color by Speed Module</a>
					</li>
					<li>
						<a href="#Size_over_Lifetime">Size over Lifetime</a>
					</li>
					<li>
						<a href="#Size_by_Speed">Size by Speed</a>
					</li>
					<li>
						<a href="#Rotation_over_Lifetime_Module">Rotation over Lifetime Module</a>
					</li>
					<li>
						<a href="#Rotation_by_Speed_Module">Rotation by Speed Module</a>
					</li>
					<li>
						<a href="#Collision_Module">Collision Module</a>
					</li>
					<li>
						<a href="#Sub_Emitters_Module">Sub Emitters Module</a>
					</li>
					<li>
						<a href="#Texture_Sheet_Animation_Module">Texture Sheet Animation Module</a>
					</li>
					<li>
						<a href="#Renderer_Module">Renderer Module</a>
					</li>
				</ol>
			<li>
				<a href="#Examples">Examples</a>
			</li>
			<li>
				<a href="#Flare">Flare</a>
				<ol class='toc-even level-2'>
					<li>
						<a href="#Base_Flare_Particle_System">Base Flare Particle System</a>
					</li>
					<li>
						<a href="#Smoke_Particle_System">Smoke Particle System</a>
					</li>
					<li>
						<a href="#Sparks_Particle_System">Sparks Particle System</a>
					</li>
				</ol>
			<li>
				<a href="#Exercise">Exercise</a>
			</li>
			<li>
				<a href="#References">References</a>
			</li>
</ol>
</div>
<div class='wptoc-end'>&nbsp;</div></div>
<span id="Introduction"><h1>Introduction</h1></span>
<p>Particle effects are an integral component of a polished video game. They add that extra flash, fizzle, and pop that makes a good game a great game.  When used correctly particle effects can add that subtle bit of realism that draws the player into the game allowing them to feel, see, and maybe even smell your gameplay.</p>
<p>In Unity (and throughout this document) the terms <strong>Particle System</strong> and <strong>Particle Effect</strong> are used interchangeably however these two terms have different meanings.</p>
<ul>
<li><strong>Particle System</strong>: This is a single <strong>Particle System</strong> component that is attached to a <strong>GameObject</strong>.</li>
<li><strong>Particle Effect</strong>: This refers to a hierarchical composition of <strong>GameObjects</strong> each with their own <strong>Particle System</strong> component.  In other words, a combination of <strong>Particle Systems</strong> which together compose a <strong>Particle Effect</strong>.</li>
</ul>
<span id="Particle_System"><h1>Particle System</h1></span>
<p>The component that provides the <strong>Shuriken Particle System</strong> functionality in Unity is the <strong>Particle System</strong> component.  You can add a particle system to your scene in multiple ways.</p>
<ul>
<li>Create a Particle System GameObject.</li>
<li>Create a GameObject and add the Particle System component.</li>
</ul>
<span id="Particle_System_GameObject"><h2>Particle System GameObject</h2></span>
<p>To create a <strong>Particle System</strong> in your scene, you can either create a new <strong>Particle System GameObject</strong> by selecting <strong>GameObject > Create Other > Particle System</strong> from the main menu.</p>
<div id="attachment_4316" class="wp-caption alignnone" style="width: 1037px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Create-New-Particle-System.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Create-New-Particle-System.png" alt="Unity - Create New Particle System" title="Unity - Create New Particle System" width="1027" height="769" class="size-full wp-image-4316" /></a><p class="wp-caption-text">Unity &#8211; Create New Particle System</p></div>
<span id="Particle_System_Component"><h2>Particle System Component</h2></span>
<p>You can also create an empty <strong>GameObject</strong> in the scene and add a <strong>Particle System</strong> component to it by selecting <strong>Component > Effects > Particle System</strong> from the main menu.</p>
<div id="attachment_4317" class="wp-caption alignnone" style="width: 1037px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Component.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Component.png" alt="Unity - Particle System Component" title="Unity - Particle System Component" width="1027" height="769" class="size-full wp-image-4317" /></a><p class="wp-caption-text">Unity &#8211; Particle System Component</p></div>
<span id="Particle_System_Properties"><h2>Particle System Properties</h2></span>
<p>Using either method should create a <strong>GameObject</strong> with a <strong>Particle System</strong> component attached to it.  In the <strong>Inspector</strong> you will see the default particle system component.</p>
<div id="attachment_4318" class="wp-caption alignnone" style="width: 318px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Inspector.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Inspector.png" alt="Unity - Particle System Inspector" title="Unity - Particle System Inspector" width="308" height="811" class="size-full wp-image-4318" /></a><p class="wp-caption-text">Unity &#8211; Particle System Inspector</p></div>
<p>I will discuss the individual modules in a later section.</p>
<span id="Preview_Panel"><h2>Preview Panel</h2></span>
<p>When you select a <strong>GameObject</strong> that has a <strong>Particle System</strong> component attached to it, the <strong>Particle Effect Preview Panel</strong> will appear in the <strong>Scene</strong> view.</p>
<div id="attachment_4327" class="wp-caption alignnone" style="width: 190px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-Effect-Preview-Panel.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-Effect-Preview-Panel.png" alt="Unity - Particle Effect Preview Panel" title="Unity - Particle Effect Preview Panel" width="180" height="88" class="size-full wp-image-4327" /></a><p class="wp-caption-text">Unity &#8211; Particle Effect Preview Panel</p></div>
<p>The <strong>Particle Effect Preview Panel</strong> allows you to <strong>Pause</strong>, <strong>Simulate</strong>, and <strong>Stop</strong> the particle effect simulation in the Scene view. </p>
<p>While the <strong>Particle Effect</strong> is being simulated or paused, you can also change the value of the <strong>Playback Time</strong> to see how the particle effect will appear at certain times. It is also possible to scrub the <strong>Playback Time</strong> so that you can see how the Particle Effect changes over time.</p>
<p><iframe width="640" height="480" src="http://www.youtube.com/embed/alEGlu3oxeo?rel=0" frameborder="0" allowfullscreen></iframe></p>
<span id="Particle_Effect_View"><h1>Particle Effect View</h1></span>
<p>You can open the Particle Effects view by selecting <strong>Window > Particle Effect</strong> from the main menu or by clicking the <strong>Open Editor&#8230;</strong> button on the <strong>Particle System</strong> component in the <strong>Inspector</strong>.</p>
<div id="attachment_4323" class="wp-caption alignnone" style="width: 1037px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Open-Particle-Effect-View.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Open-Particle-Effect-View.png" alt="Unity - Open Particle Effect View" title="Unity - Open Particle Effect View" width="1027" height="769" class="size-full wp-image-4323" /></a><p class="wp-caption-text">Unity &#8211; Open Particle Effect View</p></div>
<p>The <strong>Particle Effect</strong> view should open and display the <strong>Particle System</strong> component of the currently selected <strong>GameObject</strong>.</p>
<div id="attachment_4362" class="wp-caption alignnone" style="width: 783px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-Effect-View1.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-Effect-View1.png" alt="Unity - Particle Effect View" title="Unity - Particle Effect View" width="773" height="586" class="size-full wp-image-4362" /></a><p class="wp-caption-text">Unity &#8211; Particle Effect View</p></div>
<p>If you select a <strong>GameObject</strong> in the <strong>Scene</strong> view or the <strong>Hierarchy</strong> view that does not have a <strong>Particle System</strong> component then the <strong>Particle Effect</strong> view may be empty.</p>
<p>The <strong>Particle Effect</strong> view consists of three primary panels:</p>
<ul>
<li><strong>Toolbar</strong>: Provides buttons to Simulate/Pause and stop the Particle Effect in the Scene view</li>
<li><strong>Particle System Editor</strong>: Provides access to the properties of the <strong>Particle System</strong> components.</li>
<li><strong>Curve Editor</strong>: Allows you to manipulate the values of the Particle System properties using curves.</li>
</ul>
<span id="Toolbar"><h2>Toolbar</h2></span>
<p>The toolbar at the top of the <strong>Particle Effect</strong> view allows you to control a few aspects of the Particle Effect displayed in the scene view as well as the layout of the different panels in the Particle Effect View.</p>
<div id="attachment_4333" class="wp-caption alignnone" style="width: 846px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-Effect-View-Toolbar.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-Effect-View-Toolbar.png" alt="Unity - Particle Effect View Toolbar" title="Unity - Particle Effect View Toolbar" width="836" height="34" class="size-full wp-image-4333" /></a><p class="wp-caption-text">Unity &#8211; Particle Effect View Toolbar</p></div>
<span id="Preview_Controls"><h3>Preview Controls</h3></span>
<p>The <strong>Pause/Simulate</strong> and <strong>Stop</strong> buttons on the toolbar in the <strong>Particle Effect</strong> view allow you to start and stop the <strong>Particle Effect</strong> simulation in the <strong>Scene</strong> view and the <strong>Game</strong> view.  These buttons operate exactly the same way as the <strong>Particle Effect Preview Panel</strong> that appears in the <strong>Scene</strong> view when a <strong>GameObject</strong> with a <strong>Particle System</strong> component is selected.</p>
<span id="Show_AllSelected"><h3>Show All/Selected</h3></span>
<p>The <strong>Show: All/Selected</strong> button will toggle the view of the particle systems shown in the <strong>Particle Effect</strong> view and in the <strong>Scene</strong> view.  With <strong>Show: All</strong> selected, all of the Particle System components will be visible in the <strong>Particle Effect</strong> view and in the <strong>Scene</strong> view. With <strong>Show: Selected</strong> selected, only the currenlty selected <strong>Particle System</strong> component will appear in the <strong>Scene</strong> view and the other <strong>Particle System</strong> components will appear darker in the <strong>Particle Effect</strong> view.</p>
<div id="attachment_4338" class="wp-caption alignnone" style="width: 1035px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Parrticle-Effect-View-Show-All.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Parrticle-Effect-View-Show-All.png" alt="Unity - Particle Effect View  (Show All)" title="Unity - Particle Effect View  (Show All)" width="1025" height="586" class="size-full wp-image-4338" /></a><p class="wp-caption-text">Unity &#8211; Particle Effect View  (Show All)</p></div>
<div id="attachment_4339" class="wp-caption alignnone" style="width: 1035px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Parrticle-Effect-View-Show-Selected.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Parrticle-Effect-View-Show-Selected.png" alt="Unity - Particle Effect View  (Show Selected)" title="Unity - Particle Effect View  (Show Selected)" width="1025" height="586" class="size-full wp-image-4339" /></a><p class="wp-caption-text">Unity &#8211; Particle Effect View  (Show Selected)</p></div>
<p>You will still be able to make changes to the other <strong>Particle System</strong> components in the <strong>Particle Effect</strong> view but they will not be visible in the <strong>Scene</strong> view or the <strong>Game</strong> view and the <strong>Particle System</strong> component will appear dimmed in the <strong>Particle Effect</strong> view.</p>
<p>In addition, the currently selected <strong>Particle System</strong> component will display a blue outline to indicate that it is the currently selected <strong>Particle System</strong> (as shown in the images above).</p>
<span id="Resimulate"><h3>Resimulate</h3></span>
<p>If the <strong>Resimulate</strong> toggle button is enabled the the <strong>Particle Effect</strong> will be updated when changes to the <strong>Particle System</strong> properties are made and those changes will be immediately visible in the <strong>Scene</strong> view.  If this option is not selected then you must manually resimulate the Particle Effect to see the changes you made.</p>
<span id="Wireframe"><h3>Wireframe</h3></span>
<p>The <strong>Wireframe</strong> toggle button to preview the <strong>Particle Effect</strong> in the <strong>Scene</strong> view with wireframes turned on for the billboard and mesh particles.  In addition to the wireframe for the particles, the screen-space bounding box for each <strong>Particle System</strong> is also displayed in the <strong>Scene</strong> view. </p>
<div id="attachment_4346" class="wp-caption alignnone" style="width: 986px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-Effect-View-Wireframe.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-Effect-View-Wireframe.png" alt="Unity - Particle Effect View (Wireframe)" title="Unity - Particle Effect View (Wireframe)" width="976" height="593" class="size-full wp-image-4346" /></a><p class="wp-caption-text">Unity &#8211; Particle Effect View (Wireframe)</p></div>
<span id="Layout"><h3>Layout</h3></span>
<p>The <strong>Layout</strong> button allows you to swap between a horizontal layout and a vertical layout.  Using the horizontal layout the <strong>Particle System</strong> components will appear in the left panel and the <strong>Curve Editor</strong> will appear in the right panel.  Using the vertical layout the <strong>Particle System</strong> components will appear in the top panel and the <strong>Curve Editor</strong> will appear in the bottom panel.</p>
<div id="attachment_4348" class="wp-caption alignnone" style="width: 793px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-Effect-View-Horizontal-Layout.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-Effect-View-Horizontal-Layout.png" alt="Unity - Particle Effect View (Horizontal Layout)" title="Unity - Particle Effect View (Horizontal Layout)" width="783" height="593" class="size-full wp-image-4348" /></a><p class="wp-caption-text">Unity &#8211; Particle Effect View (Horizontal Layout)</p></div>
<div id="attachment_4349" class="wp-caption alignnone" style="width: 793px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-Effect-View-Vertical-Layout.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-Effect-View-Vertical-Layout.png" alt="Unity - Particle Effect View (Vertical Layout)" title="Unity - Particle Effect View (Vertical Layout)" width="783" height="593" class="size-full wp-image-4349" /></a><p class="wp-caption-text">Unity &#8211; Particle Effect View (Vertical Layout)</p></div>
<span id="Lock_Selected"><h3>Lock Selected</h3></span>
<p>The <strong>Lock Selected</strong> toggle button will keep the currently selected <strong>Particle Effect</strong> visible in the <strong>Particle Effect</strong> view even if you change the currently selected <strong>GameObject</strong> in the <strong>Scene</strong> view or the <strong>Hierarchy</strong> view.</p>
<span id="Curve_Editor"><h2>Curve Editor</h2></span>
<p>The <strong>Curve Editor</strong> is used to manipulate the curves for specific properties of the <strong>Particle System</strong> components.</p>
<div id="attachment_4361" class="wp-caption alignnone" style="width: 783px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-Effect-Curve-Editor.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-Effect-Curve-Editor.png" alt="Unity - Particle Effect Curve Editor" title="Unity - Particle Effect Curve Editor" width="773" height="586" class="size-full wp-image-4361" /></a><p class="wp-caption-text">Unity &#8211; Particle Effect Curve Editor</p></div>
<p>In the image above, the <strong>Start Size</strong> property of the <strong>Flare Particle System</strong> is selected and viewable in the <strong>Curve Editor</strong>.</p>
<span id="Numeric_Properties"><h2>Numeric Properties</h2></span>
<p>The <strong>Particle System</strong> components have several properties that can have a scalar numeric value (such as the <strong>Duration</strong> and <strong>Start Delay</strong> properties), or a boolean value (such as the <strong>Looping</strong> and the <strong>Prewarm</strong> properties) but there are also a few properties that allow you to select the value type of the property using the drop-down arrow shown to the right of the property (such as can be seen on the the <strong>Start Lifetime</strong>, <strong>Start Speed</strong>, and <strong>Start Size</strong> properties).</p>
<div id="attachment_4341" class="wp-caption alignnone" style="width: 589px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Property-Type-drop-down.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Property-Type-drop-down.png" alt="Unity - Particle System Property Type" title="Unity - Particle System Property Type" width="579" height="584" class="size-full wp-image-4341" /></a><p class="wp-caption-text">Unity &#8211; Particle System Property Type</p></div>
<p>There are different options in this drop-down menu depending on whether you are editing a numeric property or a color (or gradient) property.</p>
<p>For numeric properties you can change the type of the value to one of the following types:</p>
<ul>
<li><strong>Constant</strong>: Choose a single numeric value that will be used over the entire duration of the <strong>Particle System</strong> simulation or over the entire lifetime of the particle (depending on the selected module)</li>
<li><strong>Curve</strong>: The value of the property will be determined by a value on a curve at the time during the <strong>Particle System</strong> simulation or at a time during the lifetime of the particle (depending on the selected module).</li>
<li><strong>Random Between Two Constants</strong>: Allows you to specify a minimum and maximum value that will used to select a random value between those two points.</li>
<li><strong>Random Between Two Curves</strong>: Unity will create a random curve that lies between the minimum and maximum curves. The current value will be chosen based on the current time of the Particle System simulation or the lifetime of the particle depending on the selected module.</li>
</ul>
<span id="Constant"><h3>Constant</h3></span>
<p>If a numeric property has a <strong>Constant</strong> value type then the value of the property will not change over the duration of the <strong>Particle System</strong> simulation or the lifetime of the particle.  No curve will be visible in the curve editor in this case. For example, the <strong>Start Lifetime</strong> property is set to be a <strong>Constant</strong> value.</p>
<div id="attachment_4353" class="wp-caption alignnone" style="width: 866px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Numeric-Property-Constant.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Numeric-Property-Constant.png" alt="Unity - Particle System Numeric Property (Constant)" title="Unity - Particle System Numeric Property (Constant)" width="856" height="593" class="size-full wp-image-4353" /></a><p class="wp-caption-text">Unity &#8211; Particle System Numeric Property (Constant)</p></div>
<p>A Constant property will not be displayed in the <strong>Curve Editor</strong>.</p>
<span id="Curve"><h3>Curve</h3></span>
<p>If a numeric property has a <strong>Curve</strong> value type then the value of the property will be determined by the value of the curve (displayed in the curve editor) at a specific time during the simulation of the <strong>Particle System</strong> or at the lifetime of the particle (depending on the module).</p>
<div id="attachment_4356" class="wp-caption alignnone" style="width: 866px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Numeric-Property-Curve.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Numeric-Property-Curve.png" alt="Unity - Particle System Numeric Property (Curve)" title="Unity - Particle System Numeric Property (Curve)" width="856" height="593" class="size-full wp-image-4356" /></a><p class="wp-caption-text">Unity &#8211; Particle System Numeric Property (Curve)</p></div>
<p>The image above shows the <strong>Start Size</strong> property is selected and its <strong>Curve</strong> property is shown in the <strong>Curve Editor</strong>.</p>
<span id="Random_Between_Two_Constants"><h3>Random Between Two Constants</h3></span>
<p>If a numeric property is set to a <strong>Random Between Two Constants</strong> type then the value of the property will be a random value between a minimum and maximum values.</p>
<div id="attachment_4360" class="wp-caption alignnone" style="width: 783px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Numeric-Property-Random-Between-Two-Constants.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Numeric-Property-Random-Between-Two-Constants.png" alt="Unity - Particle System Numeric Property (Random Between Two Constants)" title="Unity - Particle System Numeric Property (Random Between Two Constants)" width="773" height="586" class="size-full wp-image-4360" /></a><p class="wp-caption-text">Unity &#8211; Particle System Numeric Property (Random Between Two Constants)</p></div>
<p>In the image above the <strong>Start Lifetime</strong> property is set to a <strong>Random Between Two Constants</strong> with a minimum value of 0 and a maximum value of 0.05.</p>
<p>If you select a <strong>Random Between Two Constants</strong> then there will not be a graph in the <strong>Curve Editor</strong> for that property.</p>
<span id="Random_Between_Two_Curves"><h3>Random Between Two Curves</h3></span>
<p>If a numeric property is set to a <strong>Random Between Two Curves</strong> then the value of the property will be determined by a randomly generated curve that fits within the minimum and maximum curves.</p>
<div id="attachment_4369" class="wp-caption alignnone" style="width: 783px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Numeric-Property-Random-Between-Two-Curves.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Numeric-Property-Random-Between-Two-Curves.png" alt="Unity - Particle System Numeric Property (Random Between Two Curves)" title="Unity - Particle System Numeric Property (Random Between Two Curves)" width="773" height="586" class="size-full wp-image-4369" /></a><p class="wp-caption-text">Unity &#8211; Particle System Numeric Property (Random Between Two Curves)</p></div>
<p>In this image the <strong>Start Lifetime</strong> property is shown with a minimum and maximum curve. The shaded area between the two curves is the area in which the randomly generated curve will exist.</p>
<span id="Color_Properties"><h2>Color Properties</h2></span>
<p>Some properties of the <strong>Particle System</strong> do not use numeric values but instead use colors or gradients.  For example, the <strong>Start Color</strong> property allows you to specify a color as it&#8217;s value.</p>
<p>Similar to numeric properties, color properties can be one of the following types:</p>
<ul>
<li><strong>Color</strong>: Use a single color over the duration of the <strong>Particle System</strong> simulation or the lifetime of the <strong>Particle</strong> depending on the  module.</li>
<li><strong>Gradient</strong>: Use a gradient to specify the color value over the duration of the <strong>Particle System</strong> simulation or the lifetime of the <strong>Particle</strong> depending on the  module.</li>
<li><strong>Random Between Two Colors</strong>: A random color is chosen between two color values.</li>
<li><strong>Random Between Two Gradients</strong>: A random gradient is chosen between two gradient values.</li>
</ul>
<div id="attachment_4371" class="wp-caption alignnone" style="width: 783px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Color-Property.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Color-Property.png" alt="Unity - Particle System Color Property" title="Unity - Particle System Color Property" width="773" height="586" class="size-full wp-image-4371" /></a><p class="wp-caption-text">Unity &#8211; Particle System Color Property</p></div>
<p>Color properties never use the <strong>Curve Editor</strong>. Instead, colors use the <strong>Color Picker</strong> and gradients use the <strong>Gradient Editor</strong>.</p>
<span id="Color"><h3>Color</h3></span>
<p>If you specify that a color property should be a single Color value, then you will use the <strong>Color Picker</strong> to determine the color of the property over the duration of the <strong>Particle System</strong> simulation or the lifetime of the particle depending on the module.</p>
<div id="attachment_4373" class="wp-caption alignnone" style="width: 783px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Color-Property-Colorpng.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Color-Property-Colorpng.png" alt="Unity - Particle System Color Property (Color)" title="Unity - Particle System Color Property (Color)" width="773" height="586" class="size-full wp-image-4373" /></a><p class="wp-caption-text">Unity &#8211; Particle System Color Property (Color)</p></div>
<span id="Gradient"><h3>Gradient</h3></span>
<p>If you specify that a color property should be a <strong>Gradient</strong> value, then you will use the <strong>Gradient Editor</strong> to determine the color of the property over the duration of the <strong>Particle System</strong> simulation or the lifetime of the particle depending on the module.</p>
<div id="attachment_4374" class="wp-caption alignnone" style="width: 783px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Color-Property-Gradient.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Color-Property-Gradient.png" alt="Unity - Particle System Color Property (Gradient)" title="Unity - Particle System Color Property (Gradient)" width="773" height="586" class="size-full wp-image-4374" /></a><p class="wp-caption-text">Unity &#8211; Particle System Color Property (Gradient)</p></div>
<span id="Random_Between_Two_Colors"><h3>Random Between Two Colors</h3></span>
<p>The <strong>Random Between Two Colors</strong> type allows you to specify two color values. The color that is chosen is a random color that lies somewhere between these two colors.</p>
<div id="attachment_4376" class="wp-caption alignnone" style="width: 783px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Color-Property-Random-Between-Colors.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Color-Property-Random-Between-Colors.png" alt="Unity - Particle System Color Property (Random Between Colors)" title="Unity - Particle System Color Property (Random Between Colors)" width="773" height="586" class="size-full wp-image-4376" /></a><p class="wp-caption-text">Unity &#8211; Particle System Color Property (Random Between Colors)</p></div>
<span id="Random_Between_Two_Gradients"><h3>Random Between Two Gradients</h3></span>
<p>The <strong>Random Between Two Gradients</strong> type allows you to specify two gradients. The color of the property is determined by a random gradient that is created based on the two gradients.</p>
<div id="attachment_4377" class="wp-caption alignnone" style="width: 783px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Color-Property-Random-Between-Two-Gradients.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Color-Property-Random-Between-Two-Gradients.png" alt="Unity - Particle System Color Property (Random Between Two Gradients)" title="Unity - Particle System Color Property (Random Between Two Gradients)" width="773" height="586" class="size-full wp-image-4377" /></a><p class="wp-caption-text">Unity &#8211; Particle System Color Property (Random Between Two Gradients)</p></div>
<span id="Particle_System_Modules"><h1>Particle System Modules</h1></span>
<p>Each <strong>Particle System</strong> consists of several modules that are shown in the <strong>Inspector</strong> and in the <strong>Particle Effect</strong> view. Each module controls different aspects of the <strong>Particle System</strong>.</p>
<p>The following modules are available to each <strong>Particle System</strong> component:</p>
<ul>
<li><strong>Initial Module</strong>: Defines properties that are used to initialize the particles. This module cannot be disabled.</li>
<li><strong>Emission Module</strong>: Controls the emission rate of particles.</li>
<li><strong>Shape Module</strong>: Defines the shape of the particle emitter.</li>
<li><strong>Velocity over Lifetime Module</strong>: Used to control the velocity of the particles over their lifetime.</li>
<li><strong>Limit Velocity over Lifetime Module</strong>: Limits the speed of the particles over their lifetime.</li>
<li><strong>Force over Lifetime Module</strong>: Applies a force to the particles over their lifetime.</li>
<li><strong>Color over Lifetime Module</strong>: Adjusts the color of the particles over their lifetime.</li>
<li><strong>Color by Speed Module</strong>: Adjusts the color of the particles based on their speed.</li>
<li><strong>Size over Lifetime Module</strong>: Controls the size of the particles over their lifetime.</li>
<li><strong>Size by Speed Module</strong>: Controls the size of the particles based on their speed.</li>
<li><strong>Rotation over Lifetime Module</strong>: Adjusts the particles angular velocity (rate of rotation) over their lifetime.</li>
<li><strong>Rotation by Speed Module</strong>: Adjusts the particles angular velocity (rate of rotation) based on their speed.</li>
<li><strong>Collision Module</strong>: The collision module uses a set of transforms that define collision planes for which the particles will collide with.</li>
<li><strong>Sub Emitters Module</strong>: Allows the creation of other particle systems during particle birth, death, and collision.</li>
<li><strong>Texture Sheet Animation Module</strong>: Allows you to define a sprite sheet that will be used to animate the texture of the particles over their lifetime.</li>
<li><strong>Renderer Module</strong>: Defines the properties that are required to visually render the particles (such as the particle&#8217;s Material).</li>
</ul>
<span id="Initial_Module"><h2>Initial Module</h2></span>
<p>The <strong>Initial Module</strong> is always present on every <strong>Particle System</strong> and it cannot be removed or disabled.  This module controls how each particle is initialized when it is emitted.</p>
<div id="attachment_4387" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Initial.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Initial.png" alt="Unity - Particle System Modules (Initial)" title="Unity - Particle System Modules (Initial)" width="197" height="269" class="size-full wp-image-4387" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Initial)</p></div>
<p>The <strong>Initial Module</strong> defines the following properties:</p>
<ul>
<li><strong>Duration</strong>: The duration in seconds that the particle system will emit particles.</li>
<li><strong>Looping</strong>: If you need the particle system to keep emitting particles even after the duration, then set this property to true.</li>
<li><strong>Prewarm</strong>: If the <strong>Particle System</strong> is set to <strong>Looping</strong> then enabling this parameter will cause the particle system to appear that it has already emitted particle for one cycle when it is created. This is useful for effects like fountains and waterfalls where a warm-up cycle would be visible to the player.  Only looping <strong>Particle Systems</strong> can be prewarmed.</li>
<li><strong>Start Delay</strong>: The delay in seconds before this particle system will start emitting particles.  <strong>Particle Systems</strong> that are both <strong>Looping</strong> and <strong>Prewarm</strong> cannot have a <strong>Start Delay</strong> value and in such a case this property will be disabled.</li>
<li><strong>Start Lifetime</strong>: The lifetime in seconds of the particles from the time that they are emitted.</li>
<li><strong>Start Speed</strong>: The initial speed of the particle when it is emitted.</li>
<li><strong>Start Size</strong>: The initial size of the particle when it is emitted.</li>
<li><strong>Start Rotation</strong>: The initial rotation of the particle measured in degrees when it is emitted.</li>
<li><strong>Start Color</strong>: The initial color of the particle when it is emitted.</li>
<li><strong>Gravity Modifier</strong>: The global gravity vector is first multiplied by this value before being applied to the particles.  To make particles move upwards (useful for smoke) make this value negative.</li>
<li><strong>Inherit Velocity</strong>: How much of the linear velocity of the Particle System&#8217;s Transform node is used to determine the initial velocity of the particle. This is used to simulate conservation of momentum. This only has an influence if the <strong>Particle System GameObject</strong> is moving.</li>
<li><strong>Simulation Space</strong>: Should the particle be simulated relative to <strong>Particle System Transform</strong> (<strong>Local</strong> space) node or relative to the origin of the world (<strong>World</strong> space).</li>
<li><strong>Play On Awake</strong>: Should the <strong>Particle System</strong> automatically start emitting particles as soon as it is created.</li>
<li><strong>Max Particles</strong>: The maximum number of particles that this <strong>Particle System</strong> will ever have at any moment.
</ul>
<span id="Emission_Module"><h2>Emission Module</h2></span>
<p>The <strong>Emission Moduele</strong> defines the rate at which particles are emitted from the <strong>Particle System</strong>.  The <strong>Emission Module</strong> also allows you to define particle bursts when a large number of particles are emitted at certain intervals over the duration of the <strong>Particle System</strong> simulation.</p>
<div id="attachment_4392" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Emission-Module.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Emission-Module.png" alt="Unity - Particle System Modules (Emission Module)" title="Unity - Particle System Modules (Emission Module)" width="197" height="136" class="size-full wp-image-4392" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Emission Module)</p></div>
<p>The <strong>Emission Module</strong> defines the following properties:</p>
<ul>
<li><strong>Rate</strong>: The number of particles that are emitted. If the nameless drop-down parameter under <strong>Rate</strong> is set to <strong>Time</strong> then this parameter determines the number of particles that are emitted per second. If the drop-down parameter is set to Distance then this parameter determines the number of particles that are emitted per world unit (per meter).</li>
<li><strong>Burst</strong>: The <strong>Burst</strong> parameter allows you to specify specific intervals at which extra particles should be emitted. The <strong>Time</strong> of the burst is measured in seconds since the particle simulation started.  The <strong>Particles</strong> property determines that number of particles that will be emitted at that time. Burst intervals can be added and removed using the (+) and (-) buttons next to the burst parameter.</li>
</ul>
<span id="Shape_Module"><h2>Shape Module</h2></span>
<p>The <strong>Shape Modules</strong> determines the shape of the area that emits particles. The properties that appear here are determined by the <strong>Shape</strong> parameter.</p>
<p>The Shape parameter can have one of the following values:</p>
<ul>
<li><strong>Sphere</strong>: The shape of the emitter resembles a 3D sphere.</li>
<li><strong>Hemisphere</strong>: The shape of the emitter resembles a half-sphere. The hemisphere is always in the local positive Z axis (relative to the GameObject)</li>
<li><strong>Cone</strong>: The shape of the emitter resembles a cone. The cone is always in the direction of the local positive Z axis.</li>
<li><strong>Box</strong>: The shape of the emitter resembles a 3D box.</li>
<li><strong>Mesh</strong>: Particles will be emitted from either the vertex, edge, or triangles of a mesh. The mesh can either be an asset in the project folder or a mesh that has been placed in the scene (via a GameObject).</li>
</ul>
<span id="Sphere"><h3>Sphere</h3></span>
<p>The <strong>Sphere</strong> shape emitter defines a 3D sphere that defines the shape of the area in which particles are emitted.</p>
<div id="attachment_4393" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Shape-Module-Sphere.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Shape-Module-Sphere.png" alt="Unity - Particle System Modules (Shape Module - Sphere)" title="Unity - Particle System Modules (Shape Module - Sphere)" width="197" height="85" class="size-full wp-image-4393" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Shape Module &#8211; Sphere)</p></div>
<p>The <strong>Sphere</strong> Shape emitter has the following properties:</p>
<ul>
<li><strong>Radius</strong>: The radius of the sphere in world units.</li>
<li><strong>Emit from Shell</strong>: If checked, then particles will only be emitted from the shell of the sphere (at a distance exactly equal to <strong>Radius</strong> from the origin of the <strong>Particle System</strong>). Otherwise, particles will be emitted randomly at a distance less than the <strong>Radius</strong> from the origin of the <strong>Particle System</strong>.</li>
<li><strong>Random Direction</strong>: If checked particles will be emitted in random directions. Otherwise particles will be emitted outward from the center of the sphere.</li>
</ul>
<span id="HemiSphere"><h3>HemiSphere</h3></span>
<p>The <strong>HemiSphere</strong> shape emitter will emit particle in the shape of a half-circle. The <strong>HemiSphere</strong> is always in the direction of the local Z-axis.</p>
<div id="attachment_4397" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Shape-Module-HemiSphere.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Shape-Module-HemiSphere.png" alt="Unity - Particle System Modules Shape Module - HemiSphere)" title="Unity - Particle System Modules Shape Module - HemiSphere)" width="197" height="85" class="size-full wp-image-4397" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules Shape Module &#8211; HemiSphere)</p></div>
<p>The <strong>HemiSphere</strong> Shape emitter has the following properties:</p>
<ul>
<li><strong>Radius</strong>: The radius of the hemi-sphere in world units.</li>
<li><strong>Emit from Shell</strong>: If checked, then particles will only be emitted from the shell of the hemi-sphere (at a distance exactly equal to <strong>Radius</strong> from the origin of the <strong>Particle System</strong>). Otherwise, particles will be emitted randomly at a distance less than the <strong>Radius</strong> from the origin of the <strong>Particle System</strong>.</li>
<li><strong>Random Direction</strong>: If checked particles will be emitted in random directions. Otherwise particles will be emitted outward from the center of the hemi-sphere.</li>
</ul>
<span id="Cone"><h3>Cone</h3></span>
<p>The <strong>Cone</strong> shape emitter defines a cone that has its apex at the origin of the ParticleSystem and is in the direction of the positive local Z-axis.  Particles are emitted at a random angle from the apex of the <strong>Cone</strong> in the direction of the positive local Z-axis..</p>
<div id="attachment_4399" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Shape-Module-Cone.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Shape-Module-Cone.png" alt="Unity - Particle System Modules (Shape Module - Cone)" title="Unity - Particle System Modules (Shape Module - Cone)" width="197" height="69" class="size-full wp-image-4399" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Shape Module &#8211; Cone)</p></div>
<p>The <strong>Cone</strong> shape emitter has the following properties:</p>
<ul>
<li><strong>Angle</strong>: The maximum angle that particle will be emitted in the direction of the Cone.</li>
<li><strong>Radius</strong>: This parameter allows you to determine the radius of the apex of the Cone. A radius of 0 indicates the particles will be emitted exactly at the apex of the Cone.  A larger radius will enlarge the apex in which particles can be emitted.</li>
</ul>
<div id="attachment_4404" class="wp-caption alignnone" style="width: 793px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Module-Cone-Emitter.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Module-Cone-Emitter.png" alt="Unity - Particle System Module (Cone Emitter)" title="Unity - Particle System Module (Cone Emitter)" width="783" height="496" class="size-full wp-image-4404" /></a><p class="wp-caption-text">Unity &#8211; Particle System Module (Cone Emitter)</p></div>
<p>The image shows a Cone shape emitter. The smaller end of the cone is called the apex and the larger part of the cone is called the base. The length of the cone is determined by the <strong>Start Speed</strong> parameter of the <strong>Initial Module</strong>. The particles are only emitted from the apex of the cone.</p>
<span id="Box"><h3>Box</h3></span>
<p>The shape of the emitter will resemble a 3D box.  The box will always be orientated according to the orientation of the <strong>Particle System</strong>&#8216;s <strong>Transform</strong> node.  Particles will be emitted at a random position within the volume of the box.</p>
<div id="attachment_4401" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Shape-Module-Box.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Shape-Module-Box.png" alt="Unity - Particle System Modules (Shape Module - Box)" title="Unity - Particle System Modules (Shape Module - Box)" width="197" height="101" class="size-full wp-image-4401" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Shape Module &#8211; Box)</p></div>
<p>The <strong>Box</strong> shape emitter has the following properties:</p>
<ul>
<li><strong>Box X, Y, Z</strong>: The size of the box measured in world-units in each the X, Y, and Z axis.</li>
<li><strong>Random Direction</strong>: If checked particles will be emitted in random directions. Otherwise particles will be emitted in the direction of the local Z-axis.</li>
</ul>
<span id="Mesh"><h3>Mesh</h3></span>
<p>The <strong>Mesh</strong> shape emitter allows you to specify a mesh that determines the area in which the particles are emitted.  You can specify that the particles should be emitted at a random vertex, edge, or triangle face of the mesh.</p>
<div id="attachment_4402" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Shape-Module-Mesh.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Shape-Module-Mesh.png" alt="Unity - Particle System Modules (Shape Module - Mesh)" title="Unity - Particle System Modules (Shape Module - Mesh)" width="197" height="85" class="size-full wp-image-4402" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Shape Module &#8211; Mesh)</p></div>
<p>The <strong>Mesh</strong> shape emitter has the following properties:</p>
<ul>
<li><strong>Vertex, Edge, Triangle</strong>: This drop-down box determines how the particles are emitted from the mesh. <strong>Vertex</strong> specifies that the particles will be emitted at a random vertex of the mesh. Particles will be emitted in the direction of the vertex normal.  <strong>Edge</strong> specifies that the particles will be emitted at a random edge (an edge connects any two vertices) on the mesh. Particles will be emitted at an interpolated directed based on the direction of the vertex normals of the two vertices that define the edge.  <strong>Triangle</strong> specifies that particles will be emitted from the triangle faces of the mesh. Particles will be emitted in the direction of the face normal for that triangle.</li>
</ul>
<span id="Velocity_over_Lifetime_Module"><h2>Velocity over Lifetime Module</h2></span>
<p>The <strong>Velocity over Lifetime</strong> module allows you to animate the velocity of the particle over its lifetime.</p>
<div id="attachment_4407" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Velocity-over-Lifetime.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Velocity-over-Lifetime.png" alt="Unity - Particle System Modules (Velocity over Lifetime)" title="Unity - Particle System Modules (Velocity over Lifetime)" width="197" height="53" class="size-full wp-image-4407" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Velocity over Lifetime)</p></div>
<p>The <strong>Velocity over Lifetime</strong> has the following properties:</p>
<ul>
<li><strong>X, Y, Z</strong>: The direction of the velocity vector. These values can be either a <strong>Constant</strong>, <strong>Curve</strong>, <strong>Random Between Two Constants</strong>, or a <strong>Random Between Two Curves</strong>.</li>
<li><strong>Space</strong>: Whether the velocity vector is expressed in <strong>Local-Space</strong> or <strong>World-Space</strong>.
</ul>
<span id="Limit_Velocity_over_Lifetime_Module"><h2>Limit Velocity over Lifetime Module</h2></span>
<p>The <strong>Limit Velocity over Lifetime</strong> module allows you to restrict the maximum velocity or speed of the particle over it&#8217;s lifetime.</p>
<div id="attachment_4408" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Limit-Velocity-over-Lifetime.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Limit-Velocity-over-Lifetime.png" alt="Unity - Particle System Modules (Limit Velocity over Lifetime)" title="Unity - Particle System Modules (Limit Velocity over Lifetime)" width="197" height="69" class="size-full wp-image-4408" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Limit Velocity over Lifetime)</p></div>
<p>The <strong>Limit Velocity over Lifetime</strong> module has the following properties:</p>
<ul>
<li><strong>Separate Axis</strong>: If enabled, then the next parameter will be the X, Y, and Z axis of maximum velocity the particle can have before being dampened. Otherwise the next parameter will be <strong>Speed</strong> which is used to limit the maximum magnitude of the particles velocity vector.</li>
<li><strong>X, Y, Z</strong>: If <strong>Separate Axis</strong> is enabled then these values represent the X, Y, and Z axis of the maximum velocity vector.</li>
<li><strong>Speed</strong>: If <strong>Separate Axis</strong> is not enabled then the <strong>Speed</strong> parameter determines the maximum magnitude of the particle&#8217;s velocity vector.
</ul>
<span id="Force_over_Lifetime_Module"><h2>Force over Lifetime Module</h2></span>
<p>The <strong>Force over Lifetime</strong> module is used to apply a force to the particle that will effect it&#8217;s velocity.  This can be used to create turbulent particle for example sparks from a fire or snowflakes that are influenced by wind.</p>
<div id="attachment_4409" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Force-over-Lifetime.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Force-over-Lifetime.png" alt="Unity - Particle System Modules (Force over Lifetime)" title="Unity - Particle System Modules (Force over Lifetime)" width="197" height="69" class="size-full wp-image-4409" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Force over Lifetime)</p></div>
<p>The <strong>Force over Lifetime</strong> module has the following properties:</p>
<ul>
<li><strong>X, Y, Z</strong>: The X, Y, and Z components of the force vector to apply to the particle. This value can be either <strong>Constant</strong>, <strong>Curve</strong>, <strong>Random Between Two Constants</strong>, or a <strong>Random Between Two Curves</strong>.</li>
<li><strong>Space</strong>: Determines whether the force vector is expressed in <strong>Local-Space</strong> or <strong>World-Space</strong>.</li>
<li><strong>Randomize</strong>: If enabled, the magnitude of the force vector will be randomized. This parameter only becomes available if the force parameter is set to either <strong>Random Between Two Constants</strong> or <strong>Random Between Two Curves</strong>.</li>
</ul>
<span id="Color_over_Lifetime_Module"><h2>Color over Lifetime Module</h2></span>
<p>The <strong>Color over Lifetime</strong> module allows you to specify the color of the particle over it&#8217;s lifetime.</p>
<div id="attachment_4413" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Color-over-Lifetime.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Color-over-Lifetime.png" alt="Unity - Particle System Modules (Color over Lifetime)" title="Unity - Particle System Modules (Color over Lifetime)" width="197" height="37" class="size-full wp-image-4413" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Color over Lifetime)</p></div>
<p>This module only has a single parameter called <strong>Color</strong> which can be either a <strong>Gradient</strong> or a <strong>Random Between Two Gradients</strong>.</p>
<p>For example, the following gradient will cause the particle to start as a red particle and transition through all of the colors of the rainbow and fade-out over the last 25% of it&#8217;s life.</p>
<div id="attachment_4414" class="wp-caption alignnone" style="width: 386px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Gradient-Editor.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Gradient-Editor.png" alt="" title="Unity - Gradient Editor" width="376" height="184" class="size-full wp-image-4414" /></a><p class="wp-caption-text">Unity &#8211; Gradient Editor</p></div>
<span id="Color_by_Speed_Module"><h2>Color by Speed Module</h2></span>
<p>The <strong>Color by Speed</strong> module will adjust the color of the particle based on its speed (the magnitude of the velocity vector).</p>
<div id="attachment_4415" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Color-by-Speed.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Color-by-Speed.png" alt="Unity - Particle System Modules (Color by Speed)" title="Unity - Particle System Modules (Color by Speed)" width="197" height="53" class="size-full wp-image-4415" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Color by Speed)</p></div>
<p>The <strong>Color by Speed</strong> module has the following properties:</p>
<ul>
<li><strong>Color</strong>: Defines a gradient that will be used to determine the color of the particle based on its speed. This value can be a <strong>Gradient</strong> or a <strong>Random Between Two Gradients</strong></li>
<li><strong>Speed Range</strong>: Used to map the speed of the particle to a color. If the particle has a minimum speed it will map to the color of the gradient at 0%. If the particle has the maximum speed then then it will map to the color of the gradient at 100%.</li>
</ul>
<p>For example, the following gradient will cause the particle to turn red as it approaches the maximum speed.</p>
<div id="attachment_4416" class="wp-caption alignnone" style="width: 386px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Gradient-Editor2.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Gradient-Editor2.png" alt="Unity - Gradient Editor" title="Unity - Gradient Editor" width="376" height="184" class="size-full wp-image-4416" /></a><p class="wp-caption-text">Unity &#8211; Gradient Editor</p></div>
<span id="Size_over_Lifetime"><h2>Size over Lifetime</h2></span>
<p>The <strong>Size over Lifetime</strong> module allows you to control the scale of the particle over it&#8217;s lifetime.</p>
<div id="attachment_4419" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Size-Over-Lifetime.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Size-Over-Lifetime.png" alt="Unity - Particle System Modules (Size Over Lifetime)" title="Unity - Particle System Modules (Size Over Lifetime)" width="197" height="37" class="size-full wp-image-4419" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Size Over Lifetime)</p></div>
<p>The <strong>Size over Lifetime</strong> module defines a single parameter that can be either a <strong>Curve</strong>, <strong>Random Between Two Constants</strong>, or a <strong>Random Between Two Curves</strong>.</p>
<p>For with the curve shown in the image below will start the particles with a scale of 0 at the beginning of its lifetime and steadily scale to full size near the end of the particle&#8217;s lifetime.</p>
<div id="attachment_4420" class="wp-caption alignnone" style="width: 793px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Size-Over-Lifetime-Curve.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Size-Over-Lifetime-Curve.png" alt="Unity - Particle System Modules (Size Over Lifetime Curve)" title="Unity - Particle System Modules (Size Over Lifetime Curve)" width="783" height="497" class="size-full wp-image-4420" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Size Over Lifetime Curve)</p></div>
<span id="Size_by_Speed"><h2>Size by Speed</h2></span>
<p>The <strong>Size by Speed</strong> module allows you to specify the scale of the particle based on its speed.</p>
<div id="attachment_4423" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Size-by-Speed.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Size-by-Speed.png" alt="Unity - Particle System Modules (Size by Speed)" title="Unity - Particle System Modules (Size by Speed)" width="197" height="53" class="size-full wp-image-4423" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Size by Speed)</p></div>
<p>The <strong>Size by Speed</strong> module defines the following properties:</p>
<ul>
<li><strong>Size</strong>: The size of the particle based on its speed. This parameter can be a <strong>Curve</strong>, <strong>Random Between Two Constants</strong>, or a <strong>Random Between Two Curves</strong>.</li>
<li><strong>Speed Range</strong>: Maps the maximum and minimum speeds to a value on the <strong>Speed</strong> curve.</li>
</ul>
<span id="Rotation_over_Lifetime_Module"><h2>Rotation over Lifetime Module</h2></span>
<p>The <strong>Rotation over Lifetime</strong> module controls the angular velocity of the particle over its lifetime.</p>
<div id="attachment_4426" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Rotation-over-Lifetime.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Rotation-over-Lifetime.png" alt="Unity - Particle System Modules (Rotation over Lifetime)" title="Unity - Particle System Modules (Rotation over Lifetime)" width="197" height="38" class="size-full wp-image-4426" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Rotation over Lifetime)</p></div>
<p>The <strong>Rotation over Lifetime</strong> module defines a single property called <strong>Angular Velocity</strong>.  This property controls the rotation of the particle in degrees per second over the lifetime of the particle.  This property can be a <strong>Constant</strong>, <strong>Curve</strong>, <strong>Random Between Two Constants</strong>, or a <strong>Random Between Two Curves</strong>.</p>
<span id="Rotation_by_Speed_Module"><h2>Rotation by Speed Module</h2></span>
<p>The <strong>Rotation by Speed</strong> module controls the angular velocity of the particle based on its speed (magnitude of the velocity vector).</p>
<div id="attachment_4427" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Rotation-by-Speed.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Rotation-by-Speed.png" alt="Unity - Particle System Modules (Rotation by Speed)" title="Unity - Particle System Modules (Rotation by Speed)" width="197" height="53" class="size-full wp-image-4427" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Rotation by Speed)</p></div>
<p>The <strong>Rotation by Speed</strong> module defines the following properties:</p>
<ul>
<li><strong>Angular Velocity</strong>: Used to control the rotation of the particle in degrees per second based on its speed.  This property can be a <strong>Constant</strong>, <strong>Curve</strong>, <strong>Random Between Two Constants</strong>, or a <strong>Random Between Two Curves</strong>.</li>
<li><strong>Speed Range</strong>: Maps the minimum and maximum speeds to a value in the <strong>Angular Velocity</strong> property.  If the <strong>Angular Velocity</strong> is a <strong>Constant</strong> then the <strong>Angular Velocity</strong> of the particle will be the same regardless of its speed.</li>
</ul>
<span id="Collision_Module"><h2>Collision Module</h2></span>
<p>The <strong>Collision</strong> module allows you to specify a set of <strong>Transform</strong> nodes that will be used to perform collision with the particles in this <strong>Particle System</strong>.</p>
<div id="attachment_4428" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Collision.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Collision.png" alt="Unity - Particle System Modules (Collision)" title="Unity - Particle System Modules (Collision)" width="197" height="149" class="size-full wp-image-4428" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Collision)</p></div>
<p>The <strong>Collision</strong> module defines the following properties:</p>
<ul>
<li><strong>Planes</strong>: The <strong>Planes</strong> property is an array of maximum 6 <strong>Transform</strong> nodes that are used to define the position and orientation of invisible planes in the scene. It is not necessary that the <strong>Transform</strong> that you assign in this list actually have a Plane mesh assigned to it.  The local Y-axis of the <strong>Transform</strong> node is used to determine the normal of the plane (that is, the local Y-axis of the <strong>Transform</strong> node points up in the direction of the plane). You can add up to 6 planes to this list by pressing the (+) button and you can remove planes from the list by pressing the (-) button.</li>
<li><strong>Dampen</strong>: How much of the speed of the particle is reduced when a collision occurs. A value of 0.5 will reduce the particle to half of its current speed. This property can have a value in the range 0 to 1.</li>
<li><strong>Bounce</strong>: How much the particle will bounce. If this value is 1, then 100% of the particles vertical motion is maintained. If this value is 0 then it will not bounce at all. This parameter can have a value in the range 0 to 1.</li>
<li><strong>Lifetime Loss</strong>: How much of the particle&#8217;s <strong>Start Lifetime</strong> is lost when a collision occurs. If you want the particle to die as soon as it collides then set this parameter to 1. This value can have a value in the range 0 to 1.</li>
<li><strong>Visualization</strong>: The <strong>Visualization</strong> parameter will draw virtual planes in the <strong>Scene</strong> view and the <strong>Game</strong> view to help you determine where the planes are located relative to the <strong>Particle System</strong>. These planes will not be visible in the final game.  This property can have the value <strong>Plane</strong> or <strong>Grid</strong> which determine how the virtual plane is rendered.  Adjusting the Transform node that is used to define the plane will not update the virtual plane in the Scene view or the Game view (I think this is a bug).</li>
<li><strong>Scale Plane</strong>: Determines the scale of the virtual plane.</li>
</ul>
<span id="Sub_Emitters_Module"><h2>Sub Emitters Module</h2></span>
<p>The <strong>Sub Emitters</strong> module allows you to spawn additional particle systems when a particle is emitted (birth), or if it collides with a virtual plane, or on particle death.</p>
<div id="attachment_4434" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Sub-Emitters.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Sub-Emitters.png" alt="Unity - Particle System Modules (Sub Emitters)" title="Unity - Particle System Modules (Sub Emitters)" width="197" height="69" class="size-full wp-image-4434" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Sub Emitters)</p></div>
<p>The <strong>Sub Emitters</strong> module defines the following properties:</p>
<ul>
<li><strong>Birth</strong>: The <strong>Particle System</strong> to spawn when the particle is emitted.</li>
<li><strong>Death</strong>: The <strong>Particle System</strong> to spawn when the lifetime of the particle reaches 0.</li>
<li><strong>Collision</strong>: The <strong>Particle System</strong> to spawn when the particle collides with one of the virtual planes defined in <strong>Collision</strong> module.
</ul>
<p>If you assign a <strong>Particle System</strong> as a sub emitter of another <strong>Particle System</strong> then the assigned <strong>Particle System</strong> will not start playing when the <strong>Particle Effect</strong> is started.  In addition to this, spawned <strong>Particle System</strong> will inherit the position of the particle which spawned it.</p>
<span id="Texture_Sheet_Animation_Module"><h2>Texture Sheet Animation Module</h2></span>
<p>The <strong>Texture Sheet Animation</strong> module allows you to animate the texture coordinates of the particle over its lifetime.  This module uses the size of the texture assigned to the <strong>Material</strong> property of the <strong>Renderer</strong> module (discussed next) to determine the size of each tile of the sprite sheet.</p>
<p>This module allows you to create a sprite sheet of animated sprites that will be used to created animated textures for your particles.</p>
<div id="attachment_4436" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Texture-Sheet-Animation.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Texture-Sheet-Animation.png" alt="Unity - Particle System Modules (Texture Sheet Animation)" title="Unity - Particle System Modules (Texture Sheet Animation)" width="197" height="117" class="size-full wp-image-4436" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Texture Sheet Animation)</p></div>
<p>The <strong>Texture Sheet Animation</strong> module defines the following properties:</p>
<ul>
<li><strong>Tiles</strong>: The number of tiles in the <strong>X</strong> and <strong>Y</strong> directions in the texture.  For example, the value X = 2 and Y = 1 implies that there are 2 tiles per row and 1 row of tiles in the texture.</li>
<li><strong>Animation</strong>: The tiles can be animated <strong>Whole Sheet</strong> or <strong>Single Row</strong>. If you specify <strong>Whole Sheet</strong> for this property then every tile in the texture will be used to animation the particle.  <strong>Single Row</strong> means that the particle should be animated using only a single row of tiles in the texture.</li>
<li><strong>Random Row</strong>: If checked, then one row of tiles will be chosen at random when the particle is emitted.  This parameter is only available if <strong>Single Row</strong> property is chosen.</li>
<li><strong>Row</strong>: If <strong>Random Row</strong> is not checked then this property determines the row in the texture to be used for the texture animation.</li>
<li><strong>Frame over Time</strong>: Determines the frame to use over the lifetime of the particle.  This property can be a <strong>Constant</strong>, <strong>Curve</strong>, <strong>Random Between Two Constants</strong>, or a <strong>Random Between Two Curves</strong>.  To render each frame in sequence, use a linear increasing curve.</li>
<li><strong>Cycles</strong>: How many times the animation will loop during the lifetime of the particle.  This value must be a whole number.</li>
</ul>
<p>For example, the following image contains a single row of 2 tiles:</p>
<div id="attachment_4441" class="wp-caption alignnone" style="width: 266px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Flare_Sparks_TexS.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Flare_Sparks_TexS.png" alt="Sparks (2x1)" title="Sparks (2x1)" width="256" height="128" class="size-full wp-image-4441" /></a><p class="wp-caption-text">Sparks (2&#215;1)</p></div>
<span id="Renderer_Module"><h2>Renderer Module</h2></span>
<p>The <strong>Renderer</strong> module determines how the particles are rendered to the screen.</p>
<div id="attachment_4444" class="wp-caption alignnone" style="width: 207px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Render-Module.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Particle-System-Modules-Render-Module.png" alt="Unity - Particle System Modules (Renderer Module)" title="Unity - Particle System Modules (Renderer Module)" width="197" height="182" class="size-full wp-image-4444" /></a><p class="wp-caption-text">Unity &#8211; Particle System Modules (Renderer Module)</p></div>
<p>The <strong>Renderer</strong> module defines the following properties:</p>
<ul>
<li><strong>Render Mode</strong>: Determines how the particles are rendered. The <strong>Render Mode</strong> property can have one of the following values:
<ul>
<li><strong>Billboard</strong>: The particle is rendered as a screen-aligned quad. That is, the particle will always face the viewer.</li>
<li><strong>Stretched Billboard</strong>: The particle will be screen aligned and it will be stretched according to the additional properties:
<ul>
<li><strong>Camera Scale</strong>: How much of the speed of the camera is taken into consideration when determining the stretching of the particle. Setting this parameter to 0 will not apply any additional stretching of the particle if the camera is moving.</li>
<li><strong>Speed Scale</strong>: The additional scaling of the particle along the particles velocity vector. Setting this value to 0 will not apply any additional scaling along the velocity vector of the particle.</li>
<li><strong>Length Scale</strong>: Scales the length of the particle relative to its width.  A value of 1 implies the particle is square.
</ul>
</li>
<li><strong>Horizontal Billboard</strong>: The particle will be aligned to a horizontal plane in world-space. The particles will seem to disappear when viewed from the side.</li>
<li><strong>Vertical Billboard</strong>: The particle will be aligned a vertical plane in world-space. The particles will seem to disappear when viewed from above or below.</li>
<li><strong>Mesh</strong>: Renders each particle as a mesh.
<ul>
<li><strong>Mesh</strong>: The <strong>Mesh</strong> property becomes available if the <strong>Render Mode</strong> is set to <strong>Mesh</strong>. This property determines the <strong>Mesh</strong> to use to represent the particle.  This can be a <strong>Mesh</strong> asset in the <strong>Project</strong> or a <strong>Mesh</strong> that has been assigned to a <strong>GameObject</strong> in the <strong>Scene</strong>.
</ul>
</li>
</ul>
</li>
<li><strong>Material</strong>: The Material that is used to render the particle.</li>
<li><strong>Sort Mode</strong>: Sorts the particles within the <strong>Particle System</strong>.  Particles should only be sorted when unsorted particles cause rendering artifacts.
<ul>
<li><strong>None</strong>: The particles are not sorted.</li>
<li><strong>Distance</strong>: Particles closer to the camera will be drawn after particles further away. This ensures that alpha blended particles will be rendered correctly.</li>
<li><strong>Youngest First</strong>: Particles are sorted by age and older particles will be drawn over younger particles.</li>
<li><strong>Oldest First</strong>: Particles are sorted by age and younger particles will be drawn over older particles.</li>
</ul>
</li>
<li><strong>Sorting Fudge</strong>: The <strong>Sorting Fudge</strong> property can be used to effect the draw order of <strong>Particle Systems</strong>.  <strong>Particle Systems</strong> with a lower <strong>Sorting Fudge</strong> value will more likely be drawn last and thus appear in front of other transparent objects (including other particles).</li>
<li><strong>Cast Shadows</strong>: If enabled, the particles in the Particle System will cast shadows. The particle must be rendered using an opaque material (no alpha blending).  This is useful for <strong>Mesh</strong> emitters with non-transparent materials.</li>
<li><strong>Receive Shadows</strong>: If enabled, then shadows will be cast on the particles in this <strong>Particle System</strong>. The particles must be rendered with opaque (non-transparent) material. This is useful for <strong>Mesh</strong> emitters with non-transparent materials.</li>
</ul>
<span id="Examples"><h1>Examples</h1></span>
<p>Now that we have a understanding of the underlying components that makeup a <strong>Particle System</strong> let&#8217;s put our knowledge to good use and build a simple <strong>Particle Effect</strong>.</p>
<span id="Flare"><h1>Flare</h1></span>
<p>For this example, we will go through the steps to build a simple flare particle effect.</p>
<p>Open Unity and either create a new project or open an existing project.</p>
<div id="attachment_4453" class="wp-caption alignnone" style="width: 1090px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-1.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-1.png" alt="Unity - Flare Particle Effect (1)" title="Unity - Flare Particle Effect (1)" width="1080" height="761" class="size-full wp-image-4453" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (1)</p></div>
<p>Download the following Unity Package and import it into your project.</p>
<p><a href="https://docs.google.com/open?id=0B0ND0J8HHfaXZ2RKYV9ZSkN5c0E" target="blank"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Icon-32x32.png" alt="ParticleEffects.unitypackage" title="ParticleEffects.unitypackage" width="32" height="32" class="alignleft size-full wp-image-4483" />ParticleEffects.unitypackage</a></p>
<div style="clear:both;"></div>
<p>You can import this package into your Unity project by double-clicking on the package file or by selecting  <strong>Assets > Import Package > Custom Package&#8230;</strong> from the <strong>Main Menu</strong> in Unity.</p>
<div id="attachment_4460" class="wp-caption alignnone" style="width: 635px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Import-ParticleEffects-package.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Import-ParticleEffects-package.png" alt="Unity - Import ParticleEffects package" title="Unity - Import ParticleEffects package" width="625" height="384" class="size-full wp-image-4460" /></a><p class="wp-caption-text">Unity &#8211; Import ParticleEffects package</p></div>
<p>After you click the <strong>Import</strong> button, you should get the 3 textures imported into your project:</p>
<ul>
<li><strong>Flare_Diffuse</strong>: The diffuse texture for the flare Particle System.</li>
<li><strong>Smoke_Diffuse</strong>: The diffuse texture for the smoke Particle System.</li>
<li><strong>Sparks_Tiles</strong>: A tile texture that contains 2 tiles of spark textures.</li>
</ul>
<p>After you import this package, your project might look like this:</p>
<div id="attachment_4462" class="wp-caption alignnone" style="width: 1090px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-2.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-2.png" alt="Unity - Flare Particle Effect (2)" title="Unity - Flare Particle Effect (2)" width="1080" height="761" class="size-full wp-image-4462" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (2)</p></div>
<span id="Base_Flare_Particle_System"><h2>Base Flare Particle System</h2></span>
<p>Create a new <strong>Particle System GameObject</strong> by selecting <strong>GameObject > Create Other > Particle System</strong> from the Main Menu.</p>
<div id="attachment_4467" class="wp-caption alignnone" style="width: 1090px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-3.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-3.png" alt="Unity - Flare Particle Effect (3)" title="Unity - Flare Particle Effect (3)" width="1080" height="761" class="size-full wp-image-4467" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (3)</p></div>
<p>This <strong>Particle System</strong> will be the root of the <strong>Particle Effect</strong>.  Rename this <strong>GameObject</strong> to <strong>Flare Particle Effect</strong>.</p>
<p>Open the <strong>Particle Effect</strong> view by selecting <strong>Window > Particle Effect</strong> from the <strong>Main Menu</strong> or click the <strong>Open Editor&#8230;</strong> button on the <strong>Particle System</strong> component in the <strong>Inspector</strong> view.</p>
<div id="attachment_4469" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-4.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-4.png" alt="Unity - Flare Particle Effect (4)" title="Unity - Flare Particle Effect (4)" width="1185" height="569" class="size-full wp-image-4469" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (4)</p></div>
<p>The first thing we&#8217;ll create are the Particle System that renders the sparks for our flare effect.</p>
<p>Set the following properties of the <strong>Initial Module</strong>:</p>
<ul>
<li><strong>Duration</strong>: 5.00</li>
<li><strong>Looping</strong>: true</li>
<li><strong>Prewarm</strong>: true</li>
<li><strong>Start Lifetime</strong>: 0.05</li>
<li><strong>Start Speed</strong>: 0</li>
<li><strong>Start Size</strong>: Random Between Two Curves with a max curve at 1.0 and a minimum curve set to 0.5 as shown in the image below.
<p><a href="http://3dgep.com/wp-content/uploads/2012/11/Flare-Particle-Start-Size.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Flare-Particle-Start-Size.png" alt="Flare Particle - Start Size" title="Flare Particle - Start Size" width="359" height="348" class="alignnone size-full wp-image-4471" /></a></p>
</li>
<li><strong>Start Rotation</strong>: Random Between Two Curves with a max curve set at 180 and a min curve set at 0 as shown in the image below.
<p><a href="http://3dgep.com/wp-content/uploads/2012/11/Flare-Particle-Start-Rotation.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Flare-Particle-Start-Rotation.png" alt="Flare Particle - Start Rotation" title="Flare Particle - Start Rotation" width="439" height="391" class="alignnone size-full wp-image-4473" /></a></p>
</li>
<li><strong>Start Color</strong>: Random Between Two Colors:
<ul>
<li><strong>First Color</strong>: White:
<ul>
<li><strong>Red</strong>: 255</li>
<li><strong>Green</strong>: 255</li>
<li><strong>Blue</strong>: 255</li>
<li><strong>Alpha</strong>: 255</li>
</ul>
<p><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Color-Picker-White.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Color-Picker-White.png" alt="Unity - Color Picker (White)" title="Unity - Color Picker (White)" width="206" height="346" class="size-full wp-image-4475" /></a></p>
</li>
<li><strong>Second Color</strong>: Light Orange:
<ul>
<li><strong>Red</strong>: 255</li>
<li><strong>Green</strong>: 198</li>
<li><strong>Blue</strong>: 114</li>
<li><strong>Alpha</strong>: 255</li>
</ul>
<p><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Color-Picker-light-orange.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Color-Picker-light-orange.png" alt="Unity - Color Picker (light orange)" title="Unity - Color Picker (light orange)" width="206" height="346" class="alignnone size-full wp-image-4474" /></a></p>
</li>
</ul>
</li>
<li><strong>Gravity Modifier</strong>: 0</li>
<li><strong>Inherit Velocity</strong>: 0</li>
<li><strong>Simulation Space</strong>: Local</li>
<li><strong>Play On Awake</strong>: true</li>
<li><strong>Max Particles</strong>: 2</li>
</ul>
<p>You should have something similar to what is shown below.</p>
<div id="attachment_4480" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-5.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-5.png" alt="Unity - Flare Particle Effect (5)" title="Unity - Flare Particle Effect (5)" width="1185" height="569" class="size-full wp-image-4480" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (5)</p></div>
<p>Next, make sure the Emission module is enabled and set the <strong>Rate</strong> parameter to 20.  Make sure the units are set to <strong>Time</strong>.</p>
<div id="attachment_4487" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-6.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-6.png" alt="Unity - Flare Particle Effect (6)" title="Unity - Flare Particle Effect (6)" width="1185" height="569" class="size-full wp-image-4487" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (6)</p></div>
<p>Expand the <strong>Shape</strong> module and set the following properties:</p>
<ul>
<li><strong>Shape</strong>: Sphere</li>
<li><strong>Radius</strong>: 0.01</li>
<li><strong>Emit from Shell</strong>: false</li>
<li><strong>Random Direction</strong>: false</li>
</ul>
<div id="attachment_4489" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-7.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-7.png" alt="Unity - Flare Particle Effect (7)" title="Unity - Flare Particle Effect (7)" width="1185" height="569" class="size-full wp-image-4489" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (7)</p></div>
<p>For the next step, we need to create a new <strong>Material</strong> that will be used to render the particles for this <strong>Particle System</strong>.</p>
<p>Create a new Material in the Project view and call it <strong>Flare_Sparks</strong>.</p>
<p>Set the <strong>Shader </strong>to <strong>Particles > Additive</strong> and set the <strong>Tint Color</strong> to gray.</p>
<ul>
<li><strong>Tint Color</strong>: Gray
<ul>
<li><strong>Red</strong>: 128</li>
<li><strong>Green</strong>: 128</li>
<li><strong>Blue</strong>: 128</li>
<li><strong>Alpha</strong>: 128</li>
<div id="attachment_4490" class="wp-caption alignnone" style="width: 216px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Color-Picker-Gray.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Color-Picker-Gray.png" alt="Unity - Color Picker (Gray)" title="Unity - Color Picker (Gray)" width="206" height="346" class="size-full wp-image-4490" /></a><p class="wp-caption-text">Unity &#8211; Color Picker (Gray)</p></div>
</li>
</ul>
</ul>
<p> <strong>Particle Texture</strong> property to <strong>Sparks_Tiles(2&#215;1)</strong> texture that you imported earlier.  The <strong>Flare_Sparks</strong> material should look like this:</p>
<div id="attachment_4493" class="wp-caption alignnone" style="width: 358px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare_Sparks-Material.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare_Sparks-Material.png" alt="Unity - Flare_Sparks Material" title="Unity - Flare_Sparks Material" width="348" height="566" class="size-full wp-image-4493" /></a><p class="wp-caption-text">Unity &#8211; Flare_Sparks Material</p></div>
<p>Return to the Particle System and expand the Renderer module and set the following properties:</p>
<ul>
<li>Render Mode: Billboard</li>
<li>Material: Flare_Sparks</li>
<li>Sort Mode: None</li>
<li>Sorting Fudge: 0</li>
<li>Cast Shadows: false</li>
<li>Receive Shadows: false</li>
<li>Max Particle Size: 0.5</li>
</li>
<div id="attachment_4498" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-81.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-81.png" alt="Unity - Flare Particle Effect (8)" title="Unity - Flare Particle Effect (8)" width="1185" height="569" class="size-full wp-image-4498" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (8)</p></div>
<p>You may have noticed that the sparks don&#8217;t look right yet.  This is because we are using a tiled texture but we did not specify that in the <strong>Particle System</strong>.</p>
<p>Enable the <strong>Texture Sheet Animation</strong> module and set its properties to the following values:</p>
<ul>
<li><strong>Tiles</strong>:
<ul>
<li><strong>X</strong>: 2</li>
<li><strong>Y</strong>: 1</li>
</ul>
</li>
<li><strong>Animation</strong>: Whole Sheet</li>
<li><strong>Frame over Time</strong>: Random Between Two Constants with a minimum value of 0 and a maximum value of 2.</li>
<li><strong>Cycles</strong>: 1</li>
</ul>
<div id="attachment_4496" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-9.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-9.png" alt="Unity - Flare Particle Effect (9)" title="Unity - Flare Particle Effect (9)" width="1185" height="569" class="size-full wp-image-4496" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (9)</p></div>
<span id="Smoke_Particle_System"><h2>Smoke Particle System</h2></span>
<p>Create a nested <strong>Particle System</strong> by clicking the (+) button in the <strong>Particle Effect</strong> view or add a nested <strong>GameObject</strong> to the <strong>Flare Particle Effect GameObject</strong> in the scene and add a Particle System component to it.</p>
<div id="attachment_4500" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-10.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-10.png" alt="Unity - Flare Particle Effect (10)" title="Unity - Flare Particle Effect (10)" width="1185" height="569" class="size-full wp-image-4500" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (10)</p></div>
<p>Set the properties of the <strong>Initial</strong> module to the following values:</p>
<ul>
<li><strong>Duration</strong>: 5</li>
<li><strong>Looping</strong>: true</li>
<li><strong>Prewarm</strong>: true</li>
<li><strong>Start Lifetime</strong>: 5</li>
<li><strong>Start Speed</strong>: 1</li>
<li><strong>Start Size</strong>: Random Between Two Curves with a maximum curve set to 3.4 and a minimum curve set to 1.75 as shown in the image below.
<p><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Smoke-Particle-System-Start-Size.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Smoke-Particle-System-Start-Size.png" alt="Unity - Smoke Particle System (Start Size)" title="Unity - Smoke Particle System (Start Size)" width="415" height="392" class="alignnone size-full wp-image-4502" /></a></p>
</li>
<li><strong>Start Rotation</strong>: Random Between Two Curves with a max curve set at 180 and a min curve set at 0 as shown in the image below.
<p><a href="http://3dgep.com/wp-content/uploads/2012/11/Flare-Particle-Start-Rotation.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Flare-Particle-Start-Rotation.png" alt="Flare Particle - Start Rotation" title="Flare Particle - Start Rotation" width="439" height="391" class="alignnone size-full wp-image-4473" /></a></p>
</li>
<li><strong>Start Color</strong>: Dark-gary Color with the following components:
<ul>
<li><strong>Red</strong>: 29</li>
<li><strong>Green</strong>: 29</li>
<li><strong>Blue</strong>: 29</li>
<li><strong>Alpha</strong>: 255</li>
<p><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Color-Picker-Dark-Gray.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Color-Picker-Dark-Gray.png" alt="Unity - Color Picker (Dark-Gray)" title="Unity - Color Picker (Dark-Gray)" width="206" height="346" class="alignnone size-full wp-image-4505" /></a></p>
</ul>
<li><strong>Gravity Modifier</strong>: -0.05</li>
<li><strong>Inherit Velocity</strong>: 0</li>
<li><strong>Simulation Space</strong>: Local</li>
<li><strong>Play On Awake</strong>: true</li>
<li><strong>Max Particles</strong>: 10000</li>
</ul>
<p>You should have something similar to what is shown below.</p>
<div id="attachment_4508" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-11.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-11.png" alt="Unity - Flare Particle Effect (11)" title="Unity - Flare Particle Effect (11)" width="1185" height="569" class="size-full wp-image-4508" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (11)</p></div>
<p>Next, expand the <strong>Emission</strong> module  and set its properties to the following values:</p>
<ul>
<li><strong>Rate</strong>: 5</li>
<li><strong>Units</strong>: Time</li>
<li><strong>Bursts</strong>:<br />
<table width="200">
<tr>
<th>Time</th>
<th>Particles</th>
</tr>
<tr>
<td>0.00</td>
<td>1</td>
</tr>
<tr>
<td>2.00</td>
<td>1</td>
</tr>
<tr>
<td>2.50</td>
<td>1</td>
</tr>
</table>
</li>
</ul>
<div id="attachment_4513" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-12.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-12.png" alt="Unity - Flare Particle Effect (12)" title="Unity - Flare Particle Effect (12)" width="1185" height="569" class="size-full wp-image-4513" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (12)</p></div>
<p>Enable the Shape module and set its properties to the following values:</p>
<ul>
<li>Shape: Cone</li>
<li>Angle: 25</li>
<li>Radius: 0</li>
</ul>
<div id="attachment_4514" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-13.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-13.png" alt="Unity - Flare Particle Effect (13)" title="Unity - Flare Particle Effect (13)" width="1185" height="569" class="size-full wp-image-4514" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (13)</p></div>
<p>Instead of the smoke coming straight up, I would like the smoke to come out from the side.  To modify the direction the <strong>Particle System</strong> is emitted, you must rotate the <strong>Transform</strong> node the <strong>Particle System</strong> is assigned to.</p>
<p>Select the <strong>Smoke Particle System</strong> GameObject in the Hierarchy view and rotate the game object so that it&#8217;s local Z axis is pointing to the side as shown in the image below:</p>
<div id="attachment_4515" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-14.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-14.png" alt="Unity - Flare Particle Effect (14)" title="Unity - Flare Particle Effect (14)" width="1185" height="569" class="size-full wp-image-4515" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (14)</p></div>
<p>Enable the <strong>Color over Lifetime</strong> module and set the Color property to a Gradient similar to the gradient shown in the image below.</p>
<div id="attachment_4519" class="wp-caption alignnone" style="width: 386px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Smoke-Particle-System-Color-over-Life1.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Smoke-Particle-System-Color-over-Life1.png" alt="Unity - Smoke Particle System (Color over Life)" title="Unity - Smoke Particle System (Color over Life)" width="376" height="184" class="size-full wp-image-4519" /></a><p class="wp-caption-text">Unity &#8211; Smoke Particle System (Color over Life)</p></div>
<p>You should have something similar to what is shown below.</p>
<div id="attachment_4521" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-15.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-15.png" alt="Unity - Flare Particle Effect (15)" title="Unity - Flare Particle Effect (15)" width="1185" height="569" class="size-full wp-image-4521" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (15)</p></div>
<p>Enable the <strong>Size over Lifetime</strong> module and set its <strong>Size</strong> property to a <strong>Curve</strong> resembling the curve shown below:</p>
<div id="attachment_4522" class="wp-caption alignnone" style="width: 425px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Smoke-Particle-System-Size-over-Lifetime.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Smoke-Particle-System-Size-over-Lifetime.png" alt="Unity - Smoke Particle System (Size over Lifetime)" title="Unity - Smoke Particle System (Size over Lifetime)" width="415" height="392" class="size-full wp-image-4522" /></a><p class="wp-caption-text">Unity &#8211; Smoke Particle System (Size over Lifetime)</p></div>
<p>This should result in something similar to what is shown below.</p>
<div id="attachment_4524" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-16.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-16.png" alt="Unity - Flare Particle Effect (16)" title="Unity - Flare Particle Effect (16)" width="1185" height="569" class="size-full wp-image-4524" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (16)</p></div>
<p>Enable the <strong>Rotation over Lifetime</strong> module and set the <strong>Angular Velocity</strong> parameter to a <strong>Random Between Two Curves</strong>. Set the minimum curve to -15 and the maximum curve to +15 as shown in the image below.</p>
<div id="attachment_4527" class="wp-caption alignnone" style="width: 443px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Smoke-Particle-System-Rotation-over-Lifetime.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Smoke-Particle-System-Rotation-over-Lifetime.png" alt="Unity - Smoke Particle System (Rotation over Lifetime)" title="Unity - Smoke Particle System (Rotation over Lifetime)" width="433" height="391" class="size-full wp-image-4527" /></a><p class="wp-caption-text">Unity &#8211; Smoke Particle System (Rotation over Lifetime)</p></div>
<p>To render the Smoke particle let&#8217;s create a new <strong>Material</strong> using the <strong>Smoke_Diffuse</strong> texture that was imported from the Unity package. Call the new <strong>Material</strong> <strong>Flare_Smoke</strong> and set its properties to the following values:</p>
<ul>
<li><strong>Shader</strong>: Particles/Additive</li>
<li><strong>Tint Color</strong>: White with 50% Alpha:
<ul>
<li><strong>Red</strong>: 255</li>
<li><strong>Green</strong>: 255</li>
<li><strong>Blue</strong>: 255</li>
<li><strong>Alpha</strong>: 128</li>
</ul>
</li>
<li><strong>Particle Texture</strong>: Smoke_Diffuse</li>
</ul>
<div id="attachment_4530" class="wp-caption alignnone" style="width: 300px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Smoke-Material1.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Smoke-Material1.png" alt="Unity - Flare Smoke Material" title="Unity - Flare Smoke Material" width="290" height="493" class="size-full wp-image-4530" /></a><p class="wp-caption-text">Unity &#8211; Flare Smoke Material</p></div>
<p>Expand the Renderer module and set its properties to the following values:</p>
<ul
<li><strong>Render Mode</strong>: Billboard</li>
<li><strong>Material</strong>: Flare_Smoke</li>
<li><strong>Sort Mode</strong>: Oldest First</li>
<li><strong>Sorting Fudge</strong>: 0</li>
<li><strong>Cast Shadows</strong>: false</li>
<li><strong>Receive Shadows</strong>: false</li>
<li><strong>Max Particle Size</strong>: 1</li>
</ul>
<p>This should result in something similar to what is shown below.</p>
<div id="attachment_4531" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-17.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-17.png" alt="Unity - Flare Particle Effect (17)" title="Unity - Flare Particle Effect (17)" width="1185" height="569" class="size-full wp-image-4531" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (17)</p></div>
<p>The particle effect is already looking nice but lets add one more <strong>Particle System</strong> to our <strong>Particle Effect</strong>.</p>
<span id="Sparks_Particle_System"><h2>Sparks Particle System</h2></span>
<p>For this particle system we will add some sparks that will emit from the center of the Particle Effect.</p>
<p>Add one more <strong>Particle System</strong> by clicking the (+) button in the <strong>Particle Effect</strong> view while the <strong>Flare Particle Effect</strong> is selected in the <strong>Hierarchy</strong> view. You can also add another <strong>Particle System GameObject</strong> in the scene and parent it to the <strong>Flare Particle Effect</strong> and zero the position and rotation.</p>
<p>Rename this new <strong>Particle System</strong> to <strong>Sparks Particle System</strong>.</p>
<div id="attachment_4536" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-181.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-181.png" alt="Unity - Flare Particle Effect (18)" title="Unity - Flare Particle Effect (18)" width="1185" height="569" class="size-full wp-image-4536" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (18)</p></div>
<p>The the properties of the <strong>Initial</strong> module to the following values:</p>
<ul>
<li><strong>Duration</strong>: 5.00</li>
<li><strong>Looping</strong>: true</li>
<li><strong>Prewarm</strong>: true</li>
<li><strong>Start Lifetime</strong>: 3</li>
<li><strong>Start Speed</strong>: Random Between Two Curves with a minimum curve at 3 and a maximum curve at 5 as shown in the image below:
<div id="attachment_4537" class="wp-caption alignnone" style="width: 429px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Sparks-Particle-System-Start-Lifetime.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Sparks-Particle-System-Start-Lifetime.png" alt="Unity - Sparks Particle System (Start Lifetime)" title="Unity - Sparks Particle System (Start Lifetime)" width="419" height="391" class="size-full wp-image-4537" /></a><p class="wp-caption-text">Unity &#8211; Sparks Particle System (Start Lifetime)</p></div>
</li>
<li><strong>Start Size</strong>: Random Between Two Constants with a minimum value of 0 and a maximum value of 0.03.</li>
<li><strong>Start Rotation</strong>: Random Between Two Curves with a minimum curve of -180 and a maximum curve of 180.</li>
<li><strong>Start Color</strong>: Random Between Two Colors:
<ul>
<li><strong>First Color</strong>: White
<ul>
<li><strong>Red</strong>: 255</li>
<li><strong>Green</strong>: 255</li>
<li><strong>Blue</strong>: 255</li>
<li><strong>Alpha</strong>: 255</li>
<div id="attachment_4475" class="wp-caption alignnone" style="width: 216px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Color-Picker-White.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Color-Picker-White.png" alt="Unity - Color Picker (White)" title="Unity - Color Picker (White)" width="206" height="346" class="size-full wp-image-4475" /></a><p class="wp-caption-text">Unity &#8211; Color Picker (White)</p></div>
</ul>
</li>
<li><strong>Second Color</strong>: Orange
<ul>
<li><strong>Red</strong>: 255</li>
<li><strong>Green</strong>: 144</li>
<li><strong>Blue</strong>: 0</li>
<li><strong>Alpha</strong>: 255</li>
<div id="attachment_4538" class="wp-caption alignnone" style="width: 216px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Color-Picker-Orange.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Color-Picker-Orange.png" alt="Unity - Color Picker (Orange)" title="Unity - Color Picker (Orange)" width="206" height="346" class="size-full wp-image-4538" /></a><p class="wp-caption-text">Unity &#8211; Color Picker (Orange)</p></div>
</ul>
</li>
</ul>
<li><strong>Gravity Modifier</strong>: 1</li>
<li><strong>Inherit Velocity</strong>: 0</li>
<li><strong>Simulation Space</strong>: Local</li>
<li><strong>Play On Awake</strong>: true</li>
<li><strong>Max Particles</strong>: 10000</li>
</ul>
<p>You should have something similar to the image shown below.</p>
<div id="attachment_4543" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-19.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-19.png" alt="Unity - Flare Particle Effect (19)" title="Unity - Flare Particle Effect (19)" width="1185" height="569" class="size-full wp-image-4543" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (19)</p></div>
<p>Expand the <strong>Emission</strong> module and set the <strong>Rate</strong> to <strong>50</strong> and the units to <strong>Time</strong>.</p>
<div id="attachment_4545" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-20.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-20.png" alt="Unity - Flare Particle Effect (20)" title="Unity - Flare Particle Effect (20)" width="1185" height="569" class="size-full wp-image-4545" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (20)</p></div>
<p>Expand the Shape module and set it properties to the following values:</p>
<ul>
<li><strong>Shape</strong>: Sphere</li>
<li><strong>Radius</strong>: 0.02</li>
<li><strong>Emit from Shell</strong>: false</li>
<li><strong>Random Direction</strong>: false</li>
</ul>
<div id="attachment_4546" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-21.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-21.png" alt="Unity - Flare Particle Effect (21)" title="Unity - Flare Particle Effect (21)" width="1185" height="569" class="size-full wp-image-4546" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (21)</p></div>
<p>Enable the <strong>Color over Lifetime</strong> module and set the <strong>Color</strong> property to a <strong>Gradient</strong> that resembles the gradient shown in the image below.</p>
<div id="attachment_4547" class="wp-caption alignnone" style="width: 386px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Sparks-Particle-System-Color-over-Lifetime.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Sparks-Particle-System-Color-over-Lifetime.png" alt="Sparks Particle System (Color over Lifetime)" title="Sparks Particle System (Color over Lifetime)" width="376" height="184" class="size-full wp-image-4547" /></a><p class="wp-caption-text">Sparks Particle System (Color over Lifetime)</p></div>
<p>You should have something similar to what is shown below.</p>
<div id="attachment_4549" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-22.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-22.png" alt="Unity - Flare Particle Effect (22)" title="Unity - Flare Particle Effect (22)" width="1185" height="569" class="size-full wp-image-4549" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (22)</p></div>
<p>Enable the <strong>Color by Speed</strong> module. Set the <strong>Color</strong> property to a <strong>Gradient</strong> that matches the <strong>Gradient</strong> shown in the image below. </p>
<div id="attachment_4553" class="wp-caption alignnone" style="width: 386px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Sparks-Particle-System-Color-by-Speed.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Sparks-Particle-System-Color-by-Speed.png" alt="Sparks Particle System (Color by Speed)" title="Sparks Particle System (Color by Speed)" width="376" height="184" class="size-full wp-image-4553" /></a><p class="wp-caption-text">Sparks Particle System (Color by Speed)</p></div>
<p>And set the <strong>Speed Range</strong> property to 0 to 1.</p>
<p>This should now look something like this:</p>
<div id="attachment_4554" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-23.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-23.png" alt="Unity - Flare Particle Effect (23)" title="Unity - Flare Particle Effect (23)" width="1185" height="569" class="size-full wp-image-4554" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (23)</p></div>
<p>For the sparks, we&#8217;ll create a new <strong>Material</strong> called <strong>Flare_Flare</strong>.</p>
<p>Set the Materials <strong>Shader</strong> property to <strong>Particles/Alpha Blended</strong> and set the <strong>Tint Color</strong> to gray with 50% alpha:</p>
<div id="attachment_4490" class="wp-caption alignnone" style="width: 216px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Color-Picker-Gray.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Color-Picker-Gray.png" alt="Unity - Color Picker (Gray)" title="Unity - Color Picker (Gray)" width="206" height="346" class="size-full wp-image-4490" /></a><p class="wp-caption-text">Unity &#8211; Color Picker (Gray)</p></div>
<p>Set the Material&#8217;s <strong>Particle Texture</strong> property to the <strong>Flare_Diffuse</strong> texture that you imported from the Unity package.</p>
<div id="attachment_4557" class="wp-caption alignnone" style="width: 342px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare_Flare-Material.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare_Flare-Material.png" alt="Unity - Flare_Flare Material" title="Unity - Flare_Flare Material" width="332" height="454" class="size-full wp-image-4557" /></a><p class="wp-caption-text">Unity &#8211; Flare_Flare Material</p></div>
<p>Expand the <strong>Renderer</strong> module on the <strong>Sparks Particle System</strong> and set its properties to the following values:</p>
<ul>
<li><strong>Renderer Mode</strong>: Stretched Billboard</li>
<li><strong>Camera Scale</strong>: 0</li>
<li><strong>Speed Scale</strong>: 0.05</li>
<li><strong>Length Scale</strong>: 1</li>
<li><strong>Material</strong>: Flare_Flare</li>
<li><strong>Sort Mode</strong>: None</li>
<li><strong>Sorting Fudge</strong>: 0</li>
<li><strong>Cast Shadows</strong>: false</li>
<li><strong>Receive Shadows</strong>: false</li>
<li><strong>Max Particle Size</strong>: 0.5</li>
</ul>
<p>You should have sometime similar to what is shown below:</p>
<div id="attachment_4558" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-24.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-24.png" alt="Unity - Flare Particle Effect (24)" title="Unity - Flare Particle Effect (24)" width="1185" height="569" class="size-full wp-image-4558" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (24)</p></div>
<p>At this point, the <strong>Particle Effect</strong> is finished. You can save a <strong>Prefab</strong> of the <strong>Particle Effect</strong> in your <strong>Project</strong> view so that you can create instances of it easily later.</p>
<p>There is one more effect I want to achieve and that&#8217;s to make the sparks do collision with the ground plane. This will allow the sparks to bounce off the ground and come to a rest before they fade away.</p>
<p>To achieve this, add an empty game object in the scene. Zero the position and rotation of the new <strong>GameObject</strong>.  Rename this new <strong>GameObject</strong> to <strong>Flare Collider</strong> or something similar.</p>
<p>Select the <strong>Sparks Particle System</strong> and enable the <strong>Collision</strong> module and set its properties to the following values:</p>
<ul>
<li><strong>Planes</strong>: Flare Collider (The empty GameObject we just created)</li>
<li><strong>Dampen</strong>: 0.5</li>
<li><strong>Bounce</strong>: 0.75</li>
<li><strong>Lifetime Loss</strong>: 0</li>
<li><strong>Min Kill Speed</strong>: 0</li>
<li><strong>Visualization</strong>: Solid</li>
<li><strong>Scale Plane</strong>: 1.00</li>
</ul>
<p>If the Flare Particle Effect is at the same height as the Flare Collider GameObject, then move it up a bit in the Y-axis so it is above the virtual plane.</p>
<p>You should now see the sparks from the flare bouncing off the virtual plane.</p>
<div id="attachment_4563" class="wp-caption alignnone" style="width: 1195px"><a href="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-25.png"><img src="http://3dgep.com/wp-content/uploads/2012/11/Unity-Flare-Particle-Effect-25.png" alt="Unity - Flare Particle Effect (25)" title="Unity - Flare Particle Effect (25)" width="1185" height="569" class="size-full wp-image-4563" /></a><p class="wp-caption-text">Unity &#8211; Flare Particle Effect (25)</p></div>
<p>Congratulations. Your particle effect is finished.</p>
<span id="Exercise"><h1>Exercise</h1></span>
<p>Try to create your own interesting particle effects.</p>
<span id="References"><h1>References</h1></span>
<p><a href="http://docs.unity3d.com/Documentation/Manual/ParticleSystems.html" title="Unity Manual - Particle Systems" target="_blank">Unity Manual &#8211; Particle Systems</a></p>
<p>The Particle Effect used in the article comes from the Unity 3.5 Developer Preview Page here:<br />
<a href="http://unity3d.com/unity/preview/download" title="Unity 3.5 Developer Preview" target="_blank">http://unity3d.com/unity/preview/download</a>.  There is a link to download the <a href="http://beta.unity3d.com/3.5-preview/ShurikenExamples.zip" title="ShurikenExamples.zip" target="_blank">ShurikenExamples.zip</a> file at the bottom of the page that contains the Flare particle effect as well as several other interesting particle effects.</p>
]]></content:encoded>
			<wfw:commentRss>http://3dgep.com/?feed=rss2&#038;p=4313</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Introduction to CUDA 5.0</title>
		<link>http://3dgep.com/?p=4151</link>
		<comments>http://3dgep.com/?p=4151#comments</comments>
		<pubDate>Fri, 26 Oct 2012 20:56:54 +0000</pubDate>
		<dc:creator>Jeremiah van Oosten</dc:creator>
				<category><![CDATA[CUDA]]></category>
		<category><![CDATA[General Purpose GPU Programming]]></category>
		<category><![CDATA[3.0]]></category>
		<category><![CDATA[3.5]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[compute capability]]></category>
		<category><![CDATA[introduction]]></category>
		<category><![CDATA[NVIDIA]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Visual Studio]]></category>

		<guid isPermaLink="false">http://3dgep.com/?p=4151</guid>
		<description><![CDATA[Introduction to using CUDA 5.0 with Visual Studio 2010 <a href="http://3dgep.com/?p=4151">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="attachment_4308" class="wp-caption alignleft" style="width: 160px"><a href="http://3dgep.com/wp-content/uploads/2012/10/CUDA-5-thumb.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/CUDA-5-thumb-150x150.png" alt="CUDA 5" title="CUDA 5" width="150" height="150" class="size-thumbnail wp-image-4308" /></a><p class="wp-caption-text">CUDA 5</p></div>
<p>In this article, I will introduce the reader to <a href="http://developer.nvidia.com/cuda/cuda-toolkit" title="CUDA Toolkit" target="_blank">CUDA 5.0</a>. I will briefly talk about the architecture of the Kepler <strong>GPU</strong> (<strong>G</strong>raphics <strong>P</strong>rocessing <strong>U</strong>nit) and I will show you how you can take advantage of the many <strong>CUDA</strong> (<strong>C</strong>ompute <strong>U</strong>nified <strong>D</strong>evice <strong>A</strong>rchitecture) cores in the <strong>GPU</strong> to create massively parallel programs.</p>
<p><span id="more-4151"></span></p>
<div style="clear: both;"><div class='toc wptoc'>
<h2>Table of Contents</h2>
<ol class='toc-odd level-1'>
	<li>
		<a href="#List_of_Figures">List of Figures</a>
	</li>
	<li>
		<a href="#List_of_Tables">List of Tables</a>
	</li>
	<li>
		<a href="#Introduction">Introduction</a>
	</li>
	<li>
		<a href="#Kepler_Architecture">Kepler Architecture</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Dynamic_Parallelism">Dynamic Parallelism</a>
			</li>
			<li>
				<a href="#Hyper-Q">Hyper-Q</a>
			</li>
			<li>
				<a href="#Grid_Management_Unit">Grid Management Unit</a>
			</li>
			<li>
				<a href="#NVIDIA_GPUDirect">NVIDIA GPUDirect</a>
			</li>
		</ol>
	<li>
		<a href="#Getting_Started_with_CUDA">Getting Started with CUDA</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#System_Requirements">System Requirements</a>
			</li>
			<li>
				<a href="#Verify_your_GPU">Verify your GPU</a>
			</li>
			<li>
				<a href="#Install_CUDA">Install CUDA</a>
			</li>
			<li>
				<a href="#Verify_the_Installation">Verify the Installation</a>
			</li>
			<li>
				<a href="#Run_Compiled_Sample">Run Compiled Sample</a>
			</li>
		</ol>
	<li>
		<a href="#Creating_your_First_Project">Creating your First Project</a>
	</li>
	<li>
		<a href="#Threading_Model">Threading Model</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#CUDA_Threads">CUDA Threads</a>
			</li>
			<li>
				<a href="#Matrix_Addition_Example">Matrix Addition Example</a>
			</li>
			<li>
				<a href="#The_Matrix_Addition_Kernel_Function">The Matrix Addition Kernel Function</a>
			</li>
		</ol>
	<li>
		<a href="#Thread_Synchronization">Thread Synchronization</a>
	</li>
	<li>
		<a href="#Thread_Assignment">Thread Assignment</a>
	</li>
	<li>
		<a href="#Thread_Scheduling">Thread Scheduling</a>
	</li>
	<li>
		<a href="#Thread_Divergence">Thread Divergence</a>
	</li>
	<li>
		<a href="#Memory_Model">Memory Model</a>
	</li>
	<li>
		<a href="#CUDA_Memory_Types">CUDA Memory Types</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Register">Register</a>
			</li>
			<li>
				<a href="#Local">Local</a>
			</li>
			<li>
				<a href="#Shared">Shared</a>
			</li>
			<li>
				<a href="#Global">Global</a>
			</li>
			<li>
				<a href="#Constant">Constant</a>
			</li>
		</ol>
	<li>
		<a href="#Properties_of_Memory">Properties of Memory</a>
	</li>
	<li>
		<a href="#Pointers_to_Memory">Pointers to Memory</a>
	</li>
	<li>
		<a href="#Minimize_Global_Memory_Access">Minimize Global Memory Access</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Matrix_Multiply_using_Global_Memory">Matrix Multiply using Global Memory</a>
			</li>
			<li>
				<a href="#Matrix_Multiply_using_Shared_Memory">Matrix Multiply using Shared Memory</a>
			</li>
		</ol>
	<li>
		<a href="#Resources_as_a_Limiting_Constraint">Resources as a Limiting Constraint</a>
	</li>
	<li>
		<a href="#CUDA_GPU_Occupancy_Calculator">CUDA GPU Occupancy Calculator</a>
	</li>
	<li>
		<a href="#Exercises">Exercises</a>
	</li>
	<li>
		<a href="#References">References</a>
	</li>
</ol>
</div>
<div class='wptoc-end'>&nbsp;</div></div>
<span id="List_of_Figures"><h1>List of Figures</h1></span>
<p><a href="#fig-1">Figure 1. Floating Point Operations per Second</a><br />
<a href="#fig-2">Figure 2. Memory Bandwidth</a><br />
<a href="#fig-3">Figure 3. Kepler GK110 Die</a><br />
<a href="#fig-4">Figure 4. Kepler Architecture</a><br />
<a href="#fig-5">Figure 5. Kepler Streaming Multiprocessor (SMX)</a><br />
<a href="#fig-6">Figure 6. Warp Scheduler</a><br />
<a href="#fig-7">Figure 7. Dynamic Parallelism</a><br />
<a href="#fig-8">Figure 8. Dynamic Parallelism</a><br />
<a href="#fig-9">Figure 9. Hyper-Q</a><br />
<a href="#fig-10">Figure 10. Grid Management Unit</a><br />
<a href="#fig-11">Figure 11. GPUDirect</a><br />
<a href="#fig-12">Figure 12. Control Panel</a><br />
<a href="#fig-13">Figure 13. System Manager</a><br />
<a href="#fig-14">Figure 14. Device Manager</a><br />
<a href="#fig-15">Figure 15. Command Prompt</a><br />
<a href="#fig-16">Figure 16. Device Query</a><br />
<a href="#fig-17">Figure 17. New Project Dialog</a><br />
<a href="#fig-18">Figure 18. Cuda Execution Model</a><br />
<a href="#fig-19">Figure 19. CUDA Grid Example</a><br />
<a href="#fig-20">Figure 20. Warp Scheduler</a><br />
<a href="#fig-21">Figure 21. Thread Divergence</a><br />
<a href="#fig-22">Figure 22. CUDA Memory Model</a><br />
<a href="#fig-23">Figure 23. Matrix Multiply – Global Memory</a><br />
<a href="#fig-24">Figure 24. Tiles</a><br />
<a href="#fig-25">Figure 25. Matrix Multiply – Tiles</a><br />
<a href="#fig-26">Figure 26. CUDA Occupancy Calculator</a></p>
<span id="List_of_Tables"><h1>List of Tables</h1></span>
<p><a href="#table-1">Table 1. Threading Compute Capability</a><br />
<a href="#table-2">Table 2. Memory Compute Capability</a><br />
<a href="#table-3">Table 3. Properties of Memory Types</a></p>
<span id="Introduction"><h1>Introduction</h1></span>
<p>Using the power of the <a href="http://www.nvidia.com" title="NVIDIA" target="_blank">NVIDIA</a> GPU, <a href="http://developer.nvidia.com/category/zone/cuda-zone" title="CUDA" target="_blank">CUDA</a> allows the programmer to create highly parallel applications that can perform hundreds of times faster than an equivalent program that is written to run on the CPU alone.  The <a href="http://developer.nvidia.com/cuda/cuda-toolkit" title="CUDA Toolkit" target="_blank">NVIDIA CUDA Tookit</a> provides several API&#8217;s for integrating a CUDA program into your C and C++ applications.</p>
<p>CUDA supports a heterogeneous programming environment where parts of the application code is written for the CPU and other parts of the application are written to execute on the GPU.  The application is compiled into a single executable that can run on both devices simultaneously.</p>
<p>In a CUDA intensive application, the CPU is used to allocate CUDA memory buffers, execute CUDA kernels and retrieve and analyze the result of running a kernel on the GPU.  The GPU is used to synchronously process large amounts of data or to execute a simulation that can easily be split into a large grid where each grid executes a part of the simulation in parallel.</p>
<p>The NVIDIA GPU consists of hundreds (even thousands) of CUDA cores that can work in parallel to operate on extremely large datasets in a very short time.  For this reason, the NVIDIA GPU is much more suited to work in a highly parallel nature than the CPU.</p>
<p>The image below shows the computing power of the GPU and how it compares to the CPU.  The vertical axis shows the theoretical <strong>GFLOP</strong>/s (<strong>G</strong>iga <strong>F</strong>loating <strong>P</strong>oint <strong>O</strong>perations per <strong>S</strong>econd). The horizontal axis shows the advances in technology over the years<sup><a href="#cite-1">[1]</a></sup>.</p>
<div id="fig-1" class="wp-caption alignnone" style="width: 1045px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Floating-Point-Operations-Per-Second.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Floating-Point-Operations-Per-Second.png" alt="Floating Point Operations Per Second" title="Floating Point Operations Per Second" width="1035" height="813" class="size-full wp-image-4162" /></a><p class="wp-caption-text"><strong>Figure 1.</strong> Floating Point Operations Per Second</p></div>
<p>As can be seen from the image, the latest GPU from NVIDIA (The GTX 680 at the time of this writing) can theoretically perform 3 Trillion (<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?3\times10^{12}" style="float:top;" border="0px" />) Floating Point Operations per Second (or 3 teraFLOPS)<sup><a href="#cite-1">[1]</a></sup>.</p>
<p>The GPU is also capable of transferring large amounts of data through the AGP bus. The image below shows the memory bandwidth in GB/s of the latest NVIDIA GPU compared to the latest desktop CPUs from Intel<sup><a href="cite-1">[1]</a></sup>.</p>
<div id="fig-2" class="wp-caption alignnone" style="width: 916px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Memory-Bandwidth.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Memory-Bandwidth.png" alt="Memory Bandwidth" title="Memory Bandwidth" width="906" height="751" class="size-full wp-image-4168" /></a><p class="wp-caption-text"><strong>Figure 2.</strong> Memory Bandwidth</p></div>
<p>In this article, I will introduce the latest GPU architecture from NVIDIA: <strong>Kepler</strong>. I will also introduce the CUDA threading model and demonstrate how you can execute a CUDA kernel in a C++ application.  I will also introduce the CUDA memory model and I will show how you can optimize your CUDA application by making use of shared memory.</p>
<span id="Kepler_Architecture"><h1>Kepler Architecture</h1></span>
<p><strong>Kepler</strong> is the name given to the latest line of desktop GPUs from NVIDIA.  It is currently NVIDIA&#8217;s flagship GPU replacing the <strong>Fermi</strong> architecture.</p>
<p>The Kepler GPU consits of 7.1 billion transistors<sup><a href="#cite-2">[2]</a></sup> making it the fastest and most complex microprocessor ever built.  </p>
<div id="fig-3" class="wp-caption alignnone" style="width: 592px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Kepler-GK110-Die.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/10/Kepler-GK110-Die.jpg" alt="Kepler GK110 Die" title="Kepler GK110 Die" width="582" height="605" class="size-full wp-image-4190" /></a><p class="wp-caption-text"><strong>Figure 3.</strong> Kepler GK110 Die</p></div>
<p>Despite it&#8217;s huge transistor count, the Kepler GPU is much more power efficient than its predecessor delivering up to 3x the performance per watt of the Fermi architecture<sup><a href="#cite-2">[2]</a></sup>.</p>
<p>The Kepler GPU was designed to be the highest performing GPU in the world.  The Kepler GK110 consists of 15 <strong>SMX</strong> (streaming multiprocessor) units and six 64-bit memory controllers<sup><a href="#cite-2">[2]</a></sup> as shown in the image below.</p>
<div id="fig-4" class="wp-caption alignnone" style="width: 915px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Kepler-Architecture.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/10/Kepler-Architecture.jpg" alt="Kepler Architecture" title="Kepler Architecture" width="905" height="643" class="size-full wp-image-4181" /></a><p class="wp-caption-text"><strong>Figure 4.</strong> Kepler Architecture</p></div>
<p>If we zoom into a single SMX unit, we see that each SMX unit consists of 192 single-precision CUDA cores, 64 double-precision units, 32 special function units (SFU), and 32 load/store units (LD/ST).</p>
<div id="fig-5" class="wp-caption alignnone" style="width: 729px"><a href="http://3dgep.com/wp-content/uploads/2012/10/CUDA-SMX-Unit.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/CUDA-SMX-Unit.png" alt="Kepler Streaming Multiprocessor" title="Kepler Streaming Multiprocessor" width="719" height="806" class="size-full wp-image-4187" /></a><p class="wp-caption-text"><strong>Figure 5.</strong> Kepler Streaming Multiprocessor (SMX)</p></div>
<p>The 192 single-precision CUDA cores each contain a single-precision floating-point unit (<strong>FPU</strong>) as well as a 32-bit integer arithmetic logic unit (ALU).</p>
<p>Each SMX supports 64 KB of shared memory, and 48 KB of read-only data cache.  The shared memory and the data cache are accessible to all threads executing on the same streaming multiprocessor.  Access to these memory areas is highly optimized and should be favored over accessing memory in global DRAM.</p>
<p>The SMX will schedule 32 threads in a group called a <strong>warp</strong>. Using compute capability 3.5, the GK110 GPU can schedule 64 warps per SMX for a total of 2,048 threads that can be resident in a single SMX at a time (not all threads will be active at the same time as we will see in the section describing the threading model).</p>
<p>Each SMX has four warp schedulers and eight instruction dispatch units (two dispatch units per warp scheduler) allowing four warps to be issued and executed concurrently on the streaming multiprocessor<sup><a href="#cite-2">[2]</a></sup>.</p>
<div id="fig-6" class="wp-caption alignnone" style="width: 586px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Warp-Scheduler.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Warp-Scheduler.png" alt="Warp Scheduler" title="Warp Scheduler" width="576" height="495" class="size-full wp-image-4194" /></a><p class="wp-caption-text"><strong>Figure 6.</strong> Warp Scheduler</p></div>
<span id="Dynamic_Parallelism"><h2>Dynamic Parallelism</h2></span>
<p>The GK110 GPU supports a feature called <strong>Dynamic Parallelism</strong>.  Dynamic Parallelism allows the GPU to create new work for itself by creating new kernels as they are needed without the intervention of the CPU.</p>
<div id="fig-7" class="wp-caption alignnone" style="width: 1290px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Dynamic-Parallelism.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Dynamic-Parallelism.png" alt="Dynamic Parallelism" title="Dynamic Parallelism" width="1280" height="720" class="size-full wp-image-4200" /></a><p class="wp-caption-text"><strong>Figure 7.</strong> Dynamic Parallelism</p></div>
<p>As can be seen from the image, on the left, the Fermi GPU requires the CPU to execute kernels on the GPU. On the right side of the image, the Kepler GPU is capable of launching kernels from within a kernel itself.  No intervention from the CPU is required.</p>
<p>This allows the GPU kernel to be more adaptive to dynamic branching and recursive algorithms which has some impact on the way we can implement certain functions on the GPU (such as Ray Tracing, Path Tracing and other rasterization techniques).</p>
<p>Dynamic Parallelism also allows the programmer to better load-balance their GPU based application.  Threads can by dynamically launched based on the amount of work that needs to be performed in a particular region of the grid domain.  In this case, the initial compute grid can be very coarse and the kernel can dynamically refine the grid size depending on the amount of work that needs to be performed.</p>
<div id="fig-8" class="wp-caption alignnone" style="width: 1288px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Dynamic-Parallelism-2.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Dynamic-Parallelism-2.png" alt="Dynamic Parallelism" title="Dynamic Parallelism" width="1278" height="639" class="size-full wp-image-4201" /></a><p class="wp-caption-text"><strong>Figure 8.</strong> Dynamic Parallelism</p></div>
<p>As can be seen from the image, the left grid granularity is too coarse to produce an accurate simulation. The grid in the center is too fine and many kernels are not performing any actual work.  On the right image we see that using dynamic parallelism, the grid can be dynamically refined to produce just the right balance between granularity and workload.</p>
<span id="Hyper-Q"><h2>Hyper-Q</h2></span>
<p>The Fermi architecture relied on a single hardware work queue to schedule work from multiple streams. This resulted in false intra-stream dependencies requiring dependent kernels within one stream to complete before additional kernels in a separate stream could be executed<sup><a href="#cite-2">[2]</a></sup>.</p>
<p>The Kepler GK110 resolves this false intra-stream dependency with the introduction of the <strong>Hyper-Q</strong> feature.  Hyper-Q increases the total number of hardware work-queues to 32 compared to the single work-queue of the Fermi architecture.  </p>
<div id="fig-9" class="wp-caption alignnone" style="width: 727px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Hyper-Q.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Hyper-Q.png" alt="Hyper-Q" title="Hyper-Q" width="717" height="403" class="size-full wp-image-4205" /></a><p class="wp-caption-text"><strong>Figure 9.</strong> Hyper-Q</p></div>
<p>CUDA applications that utilize multiple streams will immeditaly benifit from the multiple hardware work queues offered by the Hyper-Q feature. These stream intensive applications can see a potential increase in performance of up to 32x<sup><a href="#cite-2">[2]</a></sup>.</p>
<span id="Grid_Management_Unit"><h2>Grid Management Unit</h2></span>
<p>In order to facilitate the Dynamic Parallelism feature introduced in the GK110 GPU a new <strong>Grid Managment Unit</strong> (GMU) needed to be designed.  In the previous Fermi architecture, grids were passed to the <strong>CUDA Work Distributor</strong> (CWD) directly form the stream queue.  Since it is now possible to execute more kernels directly in a running CUDA kernel, a bi-directional communication link is required from the SMX to the CWD via the GMU.</p>
<div id="fig-10" class="wp-caption alignnone" style="width: 1008px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Grid-Management-Unit.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Grid-Management-Unit.png" alt="Grid Management Unit" title="Grid Management Unit" width="998" height="726" class="size-full wp-image-4207" /></a><p class="wp-caption-text"><strong>Figure 10.</strong> Grid Management Unit</p></div>
<span id="NVIDIA_GPUDirect"><h2>NVIDIA GPUDirect</h2></span>
<p>The Kepler GK110 supports the <strong>Remote Direct Memory Access</strong> (RDMA) feature in NVIDIA GPUDirect<sup><a href="#cite-2">[2]</a></sup>.  GPUDirect allows data to be transferred directly from one GPU to another via 3rd-party devices such as InfiniBand (IB), Network Interface Cards (NIC), and Solid-State disc drives (SSD). </p>
<div id="fig-11" class="wp-caption alignnone" style="width: 1290px"><a href="http://3dgep.com/wp-content/uploads/2012/10/GPUDirect.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/10/GPUDirect.jpg" alt="GPUDirect" title="GPUDirect" width="1280" height="720" class="size-full wp-image-4209" /></a><p class="wp-caption-text"><strong>Figure 11.</strong> GPUDirect</p></div>
<span id="Getting_Started_with_CUDA"><h1>Getting Started with CUDA</h1></span>
<p>In this article, I will use Visual Studio 2010 to create a CUDA enabled application.  The settings and configurations for Visual Studio 2008 will be similar and you should be able to follow along even if you have not yet upgraded to VS2010.</p>
<span id="System_Requirements"><h2>System Requirements</h2></span>
<p>Before you can run a CUDA program, you must make sure that your system meets the minimum requirements.</p>
<ul>
<li>CUDA-capable GPU</li>
<li>Microsoft Windows XP, Vista, 7, or 8 or Windows Server 2003 or 2008</li>
<li>NVIDIA CUDA Toolkit</li>
<li>Microsoft Visual Studio 2008 or 2010 or a corresponding version of Microsoft Visual C++ Express</li>
</ul>
<span id="Verify_your_GPU"><h2>Verify your GPU</h2></span>
<p>To verify you have a CUDA enabled GPU first check the graphics device you have installed.</p>
<ol>
<li>Open the <strong>Contol Panel</strong> from the <strong>Start Menu</strong>.
<div id="fig-12" class="wp-caption alignnone" style="width: 1082px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Control-Panel.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Control-Panel.png" alt="Control Panel" title="Control Panel" width="1072" height="726" class="size-full wp-image-4215" /></a><p class="wp-caption-text"><strong>Figure 12.</strong> Control Panel</p></div>
</li>
<li>Double-Click the <strong>System</strong> applet to open the <strong>System Control Panel</strong>.</li>
<li>In Windows XP, click on the <strong>Hardware</strong> tab then click the <strong>Device Manager</strong> button. In Windows 7 click the <strong>Device Manager</strong> link.
<p><div id="fig-13" class="wp-caption alignnone" style="width: 1082px"><a href="http://3dgep.com/wp-content/uploads/2012/10/System-Manager.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/System-Manager.png" alt="System Manager" title="System Manager" width="1072" height="726" class="size-full wp-image-4216" /></a><p class="wp-caption-text"><strong>Figure 13.</strong> System Manager</p></div>
</li>
<li>In the Device Manager window that appears, expand the <strong>Display Adapters</strong> node in the device tree.
<div id="fig-14" class="wp-caption alignnone" style="width: 805px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Device-Manager.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Device-Manager.png" alt="Device Manager" title="Device Manager" width="795" height="579" class="size-full wp-image-4218" /></a><p class="wp-caption-text"><strong>Figure 14.</strong> Device Manager</p></div>
<p>If your device is listed at <a href="https://developer.nvidia.com/cuda-gpus" title="CUDA GPUs" target="_blank">https://developer.nvidia.com/cuda-gpus</a> then you have a CUDA-capable GPU.
</li>
</ol>
<span id="Install_CUDA"><h2>Install CUDA</h2></span>
<p>Download and install the latest NVIDIA CUDA Toolkit.  The CUDA Toolkit is available at <a href="https://developer.nvidia.com/cuda-downloads" title="CUDA Downloads" target="_blank">https://developer.nvidia.com/cuda-downloads</a>.</p>
<p>At the time of this writing, the latest version of the CUDA toolkit is CUDA 5.0 Production Release.</p>
<p>The CUDA Toolkit contains the drivers and tools needed to create, build and run a CUDA application as well as libraries, header files, and CUDA samples source code and other resource<sup><a href="#cite-3">[3]</a></sup>.</p>
<p>By default, the CUDA toolkit is installed to <strong>C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v#.#</strong>, where <strong>#.#</strong> refers to the CUDA version you have installed.  For the CUDA 5.0 toolkit, the complete path to the CUDA installation will be <strong>C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v5.0</strong>.</p>
<p>The installation will include the following directories:</p>
<ul>
<li><strong>bin</strong>: This folder contains the CUDA compiler and runtime libraries (DLLs)</li>
<li><strong>include</strong>: The <strong>C</strong> header files that are needed to compile your CUDA programs.</li>
<li><strong>lib</strong>: The library files that are needed to link your CUDA programs.</li>
<li><strong>doc</strong>: This directory contains the documentation for the CUDA Toolkit such as the <strong>CUDA C Programming Guide</strong>, the <strong>CUDA C Best Practices Guide</strong> and the documentation for the different CUDA libraries that are available in the Toolkit.</li>
</ul>
<p>The CUDA Samples contain sample source code and projects for Visual Studio 2008 and Visual Studio 2010.  On Windows XP, the samples can be found in <strong>C:\Document and Settings\All Users\Application Data\NVIDIA Corporation\CUDA Samples\v#.#</strong> and for Windows Vista, Windows 7, and Windows Server 2008, the samples can be found at <strong>C:\ProgramData\NVIDIA Corporation\CUDA Samples\v#.#</strong> where #.# is the installed CUDA version.</p>
<span id="Verify_the_Installation"><h2>Verify the Installation</h2></span>
<p>Before you start creating a CUDA application, it is important to verify that your CUDA installation is working correctly.</p>
<ol>
<li>Open a <strong>Command Prompt</strong> window by going to <strong>Start Menu > All Programs > Accessories > Command Prompt</strong>
<div id="fig-15" class="wp-caption alignnone" style="width: 687px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Command-Prompt.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Command-Prompt.png" alt="Command Prompt" title="Command Prompt" width="677" height="342" class="size-full wp-image-4227" /></a><p class="wp-caption-text"><strong>Figure 15.</strong> Command Prompt</p></div>
</li>
<li>In the <strong>Command Prompt</strong> window type:
<pre>
<code>nvcc -V</code>
</pre>
<p>You should see something similar to what is shown in the Command Prompt screenshot above.  The output may differ slightly depending on the version of the CUDA Toolkit you installed but you should not get an error.
</li>
</ol>
<span id="Run_Compiled_Sample"><h2>Run Compiled Sample</h2></span>
<p>The CUDA Toolkit comes with both the source code and compiled executable for the Toolkit samples.  On Windows XP the compiled samples can be found at <strong>C:\Document and Settings\All Users\Application Data\NVIDIA Corporation\CUDA Samples\v#.#\bin\win32\Release\</strong> and on Windows 7, Windows 8, Windows Server 2003, and Windows Server 2008 the compiled samples can be found at <strong>C:\ProgramData\NVIDIA Corporation\CUDA Samples\v#.#\bin\win32\Release</strong>. On a 64-bit version of Windows, you can replace the <strong>win32</strong> with <strong>win64</strong> to run the 64-bit version of the samples.</p>
<p>Try to run the <strong>deviceQuery</strong> sample in a <strong>Command Prompt</strong> window. You should see some output similar to the following image:</p>
<div id="fig-16" class="wp-caption alignnone" style="width: 831px"><a href="http://3dgep.com/wp-content/uploads/2012/10/deviceQuery.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/deviceQuery.png" alt="deviceQuery" title="deviceQuery" width="821" height="827" class="size-full wp-image-4229" /></a><p class="wp-caption-text"><strong>Figure 16.</strong> deviceQuery</p></div>
<p>Of course the output generated on your system will be different than this (unless you also have a GeForce GT 330M mobile GPU). Of course, the important thing is that your device(s) is(are) found and the device information is displayed without any errors.</p>
<span id="Creating_your_First_Project"><h1>Creating your First Project</h1></span>
<p>For this article, I will create a CUDA application using Microsoft Visual Studio 2010. If you are still using Microsoft Visual Studio 2008 the steps will be very similar and you should still be able to follow along.</p>
<p>Open your Visual Studio IDE and create a new project.</p>
<p>As of CUDA Toolkit 5.0, Visual Studio project templates will be available that can be used to quickly create a project that is ready for creating a CUDA enabled application.  Previous to CUDA Toolkit 5.0, Visual Studio project templates were only available when you installed <strong>NVIDIA Nsight Visual Studio Edition</strong>.</p>
<p>In the <strong>New Project</strong> dialog box, select <strong>NVIDIA > CUDA</strong> from the <strong>Installed Templates</strong> pane. In the right pane, select the <strong>CUDA 5.0 Runtime</strong> template.  </p>
<div id="fig-17" class="wp-caption alignnone" style="width: 965px"><a href="http://3dgep.com/wp-content/uploads/2012/10/New-Project-Dialog.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/New-Project-Dialog.png" alt="New Project Dialog" title="New Project Dialog" width="955" height="660" class="size-full wp-image-4234" /></a><p class="wp-caption-text"><strong>Figure 17.</strong> New Project Dialog</p></div>
<p>Give your project a meaningful name such as &#8220;<strong>CUDATemplate</strong>&#8221; or something similar.</p>
<p>Click <strong>OK</strong> to create a new project.</p>
<p>This will create a new Visual Studio C++ project with a single CUDA source file called <strong>kernel.cu</strong></p>
<p>You should be able to compile and run this sample already at this point to confirm it is working.  You should get the following output:</p>
<pre>
{1,2,3,4,5} + {10,20,30,40,50} = {11,22,33,44,55}
</pre>
<p>If you got any errors or something went wrong, then you should check that do have a CUDA enabled GPU and that you installed the CUDA Toolkit prior to installing Visual Studio 2010.  Follow the steps in the previous sections again and make sure you did everything correctly.</p>
<div class="my-note">
Using the Visual Studio project template for the <strong>CUDA 5.0 Runtime</strong> will automatically configure the build settings necessary to compile a CUDA enabled application.  If you want to know how to add the configure necessary to build CUDA source files to an existing C/C++ project, then you can refer to my previous article titled <a href="http://3dgep.com/?p=1821" title="Introduction to CUDA using Visual Studio 2008">Introduction to CUDA</a> that I wrote last year. That article focuses on CUDA 4.0 using Visual Studio 2008 but the steps are almost identical for CUDA 5.0 using Visual Studio 2010.
</div>
<span id="Threading_Model"><h1>Threading Model</h1></span>
<p>The CUDA threading model describes how a kernel is executed on the GPU. </p>
<span id="CUDA_Threads"><h2>CUDA Threads</h2></span>
<p>Each kernel function is executed in a grid of threads. This grid is divided into blocks also known as thread blocks and each block is further divided into threads.</p>
<div id="fig-18" class="wp-caption alignnone" style="width: 503px"><a href="http://3dgep.com/wp-content/uploads/2011/11/Cuda-Execution-Model.png"><img src="http://3dgep.com/wp-content/uploads/2011/11/Cuda-Execution-Model.png" alt="Cuda Execution Model" title="Cuda Execution Model" width="493" height="540" class="size-full wp-image-1940" /></a><p class="wp-caption-text"><strong>Figure 18.</strong> Cuda Execution Model</p></div>
<p>In the image above we see that this example grid is divided into nine thread blocks (3&#215;3), each thread block consists of 9 threads (3&#215;3) for a total of 81 threads for the kernel grid.</p>
<p>This image only shows 2-dimensional grid, but if the graphics device supports compute capability 2.0 or higher, then the grid of thread blocks can actually be partitioned into 1, 2 or 3 dimensions, otherwise if the device supports compute capability 1.x, then thread blocks can be partitioned into 1, or 2 dimensions (in this case, then the 3rd dimension should always be set to 1).</p>
<p>The thread block is partitioned into individual threads and for all compute capabilities, threads in a block can be partitioned into 1, 2, or 3 dimensions. The maximum number of threads that can be assigned to a thread block is 512 for devices with compute capability 1.x and 1024 threads for devices that support compute capability 2.0 and higher.</p>
<table id="table-1" style="border-width: 2px; border-color: #000000; border-style: solid;" border="2" frame="box">
<caption><strong>Table 1.</strong> Threading Compute Capability</caption>
<tbody>
<tr style="background-color: #a9a9a9;">
<td style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;"><strong>Technical Specifications</strong></td>
<td align="center" style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;"><strong>1.0</strong></td>
<td align="center" style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;"><strong>1.1</strong></td>
<td align="center" style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;"><strong>1.2</strong></td>
<td align="center" style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;"><strong>1.3</strong></td>
<td align="center" style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;"><strong>2.x</strong></td>
<td align="center" style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;"><strong>3.0</strong></td>
<td align="center" style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;"><strong>3.5</strong></td>
</tr>
<tr>
<td style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;">Maximum dimensionality of a grid of thread blocks.</td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;" colspan="4">2</td>
<td colspan="3" style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">3</td>
</tr>
<tr>
<td style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;">Maximum x-, dimension of a grid of thread blocks.</td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;" colspan="5">65535</td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;" colspan="2">2<sup>31</sup>-1</td>
</tr>
<tr>
<td style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;">Maximum y- or z-dimension of a grid of thread blocks.</td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;" colspan="7">65535</td>
</tr>
<tr>
<td style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;">Maximum dimensionality of a thread block.</td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;" colspan="7">3</td>
</tr>
<tr>
<td style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;">Maximum x- or y-dimension of a block.</td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;" colspan="4">512</td>
<td colspan="3" style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">1024</td>
</tr>
<tr>
<td style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;">Maximum z-dimension of a block.</td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;" colspan="7">64</td>
</tr>
<tr>
<td style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;">Maximum number of threads per block.</td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;" colspan="4">512</td>
<td colspan="3" style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">1024</td>
</tr>
<tr>
<td style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;">Warp size.</td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;" colspan="7">32</td>
</tr>
<tr>
<td style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;">Maximum number of resident blocks per multiprocessor.</td>
<td colspan="5" style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">8</td>
<td colspan="2" style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">16</td>
</tr>
<tr>
<td style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;">Maximum number of resident warps per multiprocessor.</td>
<td colspan="2" style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">24</td>
<td colspan="2" style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">32</td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">48</td>
<td colspan="2" style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">64</td>
</tr>
<tr>
<td style="text-align: left; border-width: 1px; border-color: #000000; border-style: solid;">Maximum number of resident threads per multiprocessor.</td>
<td colspan="2" style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">768</td>
<td colspan="2" style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">1024</td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">1536</td>
<td colspan="2" style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">2048</td>
</tr>
</tbody>
</table>
<p>The number of blocks within a gird can be determined within a kernel by using the built-in variable <strong>gridDim</strong> and the number of threads within a block can be determined by using the built-in variable <strong>blockDim</strong>.</p>
<p>A thread block is uniquely identified in a kernel function by using the built-in variable <strong>blockIdx</strong> and a thread within a block is uniquely identified in a kernel function by using the built-in variable <strong>threadIdx</strong>.</p>
<p>The built-in variables <strong>gridDim</strong>, <strong>blockDim</strong>, <strong>blockIdx</strong>, and <strong>threadIdx</strong> are each 3-component structs with members x, y, z.</p>
<p>With a 1-D kernel, the unique thread ID within a block is the same as the x component of the threadIdx variable.</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?threadID=threadIdx.x" style="float:top;" border="0px" />
<p>and the unique block ID within a grid is the same as the x component of the blockIdx variable:</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?blockID=blockIdx.x" style="float:top;" border="0px" />
<p>To determine the unique thread ID in a 2-D block, you would use the following formula:</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?threadID=(threadIdx.y*blockDim.x)+threadIdx.x" style="float:top;" border="0px" />
<p>and to determine the unique block ID within a 2-D grid, you would use the following formula:</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?blockID=(blockIdx.y*gridDim.x)+blockIdx.x" style="float:top;" border="0px" />
<p>I&#8217;ll leave it as an exercise for the reader to determine the formula to compute the unique thread ID and block ID in a 3D grid.</p>
<span id="Matrix_Addition_Example"><h2>Matrix Addition Example</h2></span>
<p>Let&#8217;s take a look at an example kernel that one might execute.</p>
<p>Let&#8217;s assume we want to implement a kernel function that adds two matrices and stores the result in a 3rd.</p>
<p>The general formula for matrix addition is:</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?\begin{matrix}C &amp;&amp; = &amp;&amp; A+B \\ c_{i,j} &amp;&amp; = &amp;&amp; a_{i,j}+b_{i,j}\end{matrix}" style="float:top;" border="0px" />
<p>That is, the sum of matrix <strong>A</strong> and matrix <strong>B</strong> is the sum of the components of matrix <strong>A</strong> and matrix <strong>B</strong>.</p>
<p>Let&#8217;s first write the host version of this method that we would execute on the CPU.</p>
<div class="notranslate">
<pre class="brush:cpp;toolbar:false;first-line:1;" title="MatrixAdd.cpp">
void MatrixAddHost( float* C, float* A, float* B, unsigned int matrixDim )
{
    for( unsigned int j = 0; j &lt; matrixDim; ++j )
    {
        for ( unsigned int i = 0; i &lt; matrixDim; ++i )
        {
            unsigned int index = ( j * matrixDim) + i;
            C[index] = A[index] + B[index];
        }
    }
}</pre>
</div>
<p>This is a pretty standard method that loops through the rows and columns of a matrix and adds the components and stores the results in a 3rd. Now let&#8217;s see how we might execute this kernel on the GPU using CUDA.</p>
<p>First, we need to think of the problem domain. I this case, the domain is trivial: it is the components of a matrix. Since we are operating on 2-D arrays, it seems reasonable to split our domain into two dimensions; one for the rows, and another for the columns of the matrices.</p>
<p>We will assume that we are working on square matrices. This simplifies the problem but mathematically matrix addition only requires that the two matrices have the same number of rows and columns but does not have the requirement that the matrices must be square.</p>
<p>Since we know that a kernel is limited to 512 threads/block with compute capability 1.x and 1024 threads/block with compute capability 2.x and 3.x, then we know we can split our job into square thread blocks each consisting of 16&#215;16 threads (256 threads per block) with compute capability 1.x and 32&#215;32 threads (1024 threads per block) with compute capability 2.x and 3.x.</p>
<p>If we limit the size of our matrix to no larger than 16&#215;16, then we only need a single block to compute the matrix sum and our kernel execution configuration might look something like this:</p>
<div class="notranslate">
<pre class="brush:cpp;toolbar:false;first-line:1;" title="main.cpp">
    dim3 gridDim( 1, 1, 1 );
    dim3 blockDim( matrixDim, matrixDim, 1 );
    MatrixAddDevice&lt;&lt;&lt;gridDim, blockDim&gt;&gt;&gt;( C, A, B, matrixDim );
</pre>
</div>
<p>In this simple case, the kernel grid consists of only a single block with <em>matrixDim</em> x <em>matrixDim</em> threads.</p>
<p>However, if we want to sum matrices larger than 512 components, then we must split our problem domain into smaller groups that can be processed in multiple blocks.</p>
<p>Let&#8217;s assume that we want to limit our blocks to execute in 16&#215;16 (256) threads. We can determine the number of blocks that will be required to operate on the entire array by dividing the size of the matrix dimension by the maximum number of threads per block and round-up to the nearest whole number:</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?blocks=Ceiling\lceil{\frac{matrixDim}{16}}\rceil" style="float:top;" border="0px" />
<p>And we can determine the number of threads per block by dividing the size of the matrix dimension by the number of blocks and round-up to the nearest whole number:</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?threads=Ceiling\lceil{\frac{matrixDim}{blocks}}\rceil" style="float:top;" border="0px" />
<p>So for example, for a <strong>4&#215;4</strong> matrix, we would get</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?\begin{matrix}blocks &amp;&amp; = &amp;&amp; \lceil\frac{4}{16}\rceil \\ blocks &amp;&amp; = &amp;&amp; \lceil{0.25}\rceil \\ blocks &amp;&amp; = &amp;&amp; 1\end{matrix}" style="float:top;" border="0px" />
<p>and the number of threads is computed as:</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?\begin{matrix}threads &amp;&amp; = &amp;&amp; \lceil\frac{4}{1}\rceil \\ threads &amp;&amp; = &amp;&amp; 4\end{matrix}" style="float:top;" border="0px" />
<p>resulting in a <strong>1&#215;1</strong> grid of <strong>4&#215;4</strong> thread blocks for a total of <strong>16</strong> threads.</p>
<p>Another example a <strong>512&#215;512</strong> matirx, we would get:</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?\begin{matrix}blocks &amp;&amp; = &amp;&amp; \lceil\frac{512}{16}\rceil \\ blocks &amp;&amp; = &amp;&amp; \lceil{32}\rceil \\ blocks &amp;&amp; = &amp;&amp; 32\end{matrix}" style="float:top;" border="0px" />
<p>and the number of threads is computed as:</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?\begin{matrix}threads &amp;&amp; = &amp;&amp; \lceil\frac{512}{32}\rceil \\ threads &amp;&amp; = &amp;&amp; 16\end{matrix}" style="float:top;" border="0px" />
<p>resulting in a <strong>32&#215;32</strong> grid of <strong>16&#215;16</strong> thread blocks for a total of <strong>262,144</strong> threads.</p>
<p>The host code to setup the kernel granularity might look like this:</p>
<div class="notranslate">
<pre class="brush:cpp;toolbar:false;first-line:1;" title="main.cpp">
    size_t blocks = ceilf( matrixDim / 16.0f );
    dim3 gridDim( blocks, blocks, 1 );
    size_t threads = ceilf( matrixDim / (float)blocks );
    dim3 blockDim( threads, threads, 1 );

    MatrixAddDevice&lt;&lt;&lt; gridDim, blockDim &gt;&gt;&gt;( C, A, B, matrixDim );
</pre>
</div>
<div class="my-note">
You may have noticed that if the size of the matrix does not fit nicely into equally divisible blocks, then we may get more threads than are needed to process the array. It is not possible to configure a gird of thread blocks with 1 block containing less threads than the others. The only way to solve this is to execute multiple kernels &#8211; one that handles all the equally divisible blocks, and a 2nd kernel invocation that handles the partial block. The other solution to this problem is simply to ignore any of the threads that are executed outside of our problem domain which is generally the easier (and more efficient) than invoking multiple kernels (this should be profiled to be proven).
</div>
<span id="The_Matrix_Addition_Kernel_Function"><h2>The Matrix Addition Kernel Function</h2></span>
<p>On the device, one kernel function is created for every thread in the problem domain (the matrix elements). We can use the built-in variables <strong>gridDim</strong>, <strong>blockDim</strong>, <strong>blockIdx</strong>, and <strong>threadIdx</strong>, to identify the current matrix element that the current kernel is operating on.</p>
<p>If we assume we have a <strong>9&#215;9</strong> matrix and we split the problem domain into <strong>3&#215;3</strong> blocks each consisting of <strong>3&#215;3</strong> threads as shown in the CUDA Grid below, then we could compute the <em>i</em><sup>th</sup> column and the <em>j</em><sup>th</sup> row of the matrix with the following formula:</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?\begin{matrix}i &amp;&amp; = &amp;&amp; (blockDim.x*blockIdx.x)+threadIdx.x \\ j &amp;&amp; = &amp;&amp; (blockDim.y*blockIdx.y)+threadIdx.y\end{matrix}" style="float:top;" border="0px" />
<p>So for thread <strong>(0,0)</strong> of block <strong>(1,1)</strong> of our <strong>9&#215;9</strong> matrix, we would get:</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?\begin{matrix}i &amp;&amp; = &amp;&amp; (3*1)+0 \\ i &amp;&amp; = &amp;&amp; 3\end{matrix}" style="float:top;" border="0px" />
<p>for the column and:</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?\begin{matrix}j &amp;&amp; = &amp;&amp; (3*1)+0 \\ j &amp;&amp; = &amp;&amp; 3\end{matrix}" style="float:top;" border="0px" />
<p>for the row.</p>
<p>The index into the 1-D buffer that store the matrix is then computed as:</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?index=(matrixDim*i)+j" style="float:top;" border="0px" />
<p>and substituting gives:</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?\begin{matrix}index &amp;&amp; = &amp;&amp; (matrixDim*3)+3 \\ index &amp;&amp; = &amp;&amp; (9*3)+3 \\ index &amp;&amp; = &amp;&amp; 30\end{matrix}" style="float:top;" border="0px" />
<p>Which is the correct element in the matrix. This solution assumes we are accessing the matrix in row-major order.</p>
<div id="fig-19" class="wp-caption alignnone" style="width: 503px"><a href="http://3dgep.com/wp-content/uploads/2011/11/Cuda-Execution-Model-2.png"><img src="http://3dgep.com/wp-content/uploads/2011/11/Cuda-Execution-Model-2.png" alt="CUDA Grid Example" title="CUDA Grid Example" width="493" height="540" class="size-full wp-image-1971" /></a><p class="wp-caption-text"><strong>Figure 19.</strong> CUDA Grid Example</p></div>
<p>Let&#8217;s see how we might implement this in the kernel.</p>
<div class="notranslate">
<pre class="brush:cpp;toolbar:false;first-line:1;" title="MatrixAdd.cu">
__global__ void MatrixAddDevice( float* C, float* A, float* B, unsigned int matrixDim )
{
    unsigned int column = ( blockDim.x * blockIdx.x ) + threadIdx.x;
    unsigned int row    = ( blockDim.y * blockIdx.y ) + threadIdx.y;

    unsigned int index = ( matrixDim * row ) + column;
    if ( index &lt; matrixDim * matrixDim ) // prevent reading/writing array out-of-bounds.
    {
        C[index] = A[index] + B[index];
    }
}
</pre>
</div>
<p>The kernel function is defined using the <strong>__global__</strong> declaration specifier.  This specifier is used to identify a function that should execute on the device.  Optionally you can also specify host functions with the <strong>__host__</strong> declaration specifier within a CUDA source file but this is implied if no specifier is applied to the function declaration.</p>
<p>On line 3, and 4 we compute the column and row of the matrix we are operating on using the formulas shown earlier.</p>
<p>On line 6, the 1-d index in the matrix array is computed based on the size of a single dimension of the square matrix.</p>
<p>We must be careful that we don&#8217;t try to read or write out of the bounds of the matrix. This might happen if the size of the matrix does not fit nicely into the size of the CUDA grid (in the case of matrices whose size is not evenly divisible by 16) To protect the read and write operation, on line 7 we must check that the computed index does not exceed the size of our array.</p>
<span id="Thread_Synchronization"><h1>Thread Synchronization</h1></span>
<p>CUDA provides a synchronization barrier for all threads in a block through the <strong>__syncthreads()</strong> method. A practical example of thread synchronization will be shown in a later article about optimization a CUDA kernel, but for now it&#8217;s only important that you know this functionality exists.</p>
<p>Thread synchronization is only possible across all threads in a block but not across all threads running in the grid. By not allowing threads across blocks to be synchronized, CUDA enables multiple blocks to be executed on other streaming multiprocessors (SM) in any order. The queue of blocks can be distributed to any SM without having to wait for blocks from another SM to be complete. This allows the CUDA enabled applications to scale across platforms that have more SM at it&#8217;s disposal, executing more blocks concurrently than another platforms with less SM&#8217;s.</p>
<p>Thread synchronization follows strict synchronization rules. All threads in a block must hit the synchronization point or none of them must hit synchronization point.</p>
<p>Give the following code block:</p>
<div class="notranslate">
<pre class="brush:cpp;toolbar:false;first-line:1;" title="sample.cu">if ( threadID % 2 == 0 )
{
    __syncthreads();
}
else
{
    __syncthreads();
}</pre>
</div>
<p>will cause the threads in a block to wait indefinitely for each other because the two occurrences of <strong>__syncthreads</strong> are considered separate synchronization points and all threads of the same block must hit the same synchronization point, or all of them must not hit it.</p>
<span id="Thread_Assignment"><h1>Thread Assignment</h1></span>
<p>When a kernel is invoked, the CUDA runtime will distribute the blocks across the SM&#8217;s on the device. With compute compatibility 1.x and 2.x a maximum of 8 blocks will be assigned to each SM and with compute compatibility 3.x a maximum of 16 blocks will be assigned to each SM as long as there are enough resources (registers, shared memory, and threads) to execute all the blocks. In the case where there are not enough resources on the SM, then the CUDA runtime will automatically assign less blocks per SM until the resource usage is below the maximum per SM.</p>
<p>The total number of blocks that can be executed concurrently is dependent on the device. In the case of the Fermi architecture a total of 16 SM&#8217;s can concurrently handle 8 blocks for a total of 128 blocks executing concurrently on the device. Kepler devices can handle 16 thread blocks per SMX for a total of 240 thread blocks that can execute concurrently on a single device.</p>
<p>Both the Fermi and Kepler architecture support thread blocks consisting of at most 1024 threads. The Fermi device can support a maximum of 48 warps per SM. The Kepler architecture increases the amount of resident warps per SMX to 64.</p>
<p>The Fermi device can support a maximum of 1,536 resident threads (32&#215;48) per SM. Kepler supports 2,048 threads per SMX (32&#215;64).  With 15 SMX units, the Kepler GPU can have a total of 30,720 resident threads on the device. This does not mean that every clock tick the devices is executing 30,720 instruction simultaneously (there are only 2,880 CUDA Cores on the GK110 device). In order to understand how the blocks are actually executed on the device, we must look one step further to see how the threads of a block are actually scheduled on the SM&#8217;s.</p>
<span id="Thread_Scheduling"><h1>Thread Scheduling</h1></span>
<p>When a block is assigned to a SMX, it is further divided into groups of 32 threads called a <strong>warp</strong>. Warp scheduling is different depending on the platform, but if we take a look at the Kepler architecture, we see that a single SMX consists of 192 CUDA cores (a CUDA core is also sometimes referred to a streaming processor or <strong>SP</strong> for short).</p>
<p>Each SMX in the Kepler architecture features four warp schedulers allowing four warps to be issued and executed concurrently. Kepler&#8217;s quad-warp scheduler selects four warps and issues two independent instructions from each warp every cycle<sup><a href="#cite-2">[2]</a></sup>.</p>
<div id="fig-20" class="wp-caption alignnone" style="width: 586px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Warp-Scheduler.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Warp-Scheduler.png" alt="Warp Scheduler" title="Warp Scheduler" width="576" height="495" class="size-full wp-image-4194" /></a><p class="wp-caption-text"><strong>Figure 20.</strong> Warp Scheduler</p></div>
<p>You might be wondering why it would be useful to schedule 16 blocks of a maximum of 1024 threads if the SMX only has 192 cuda cores? The answer is that each instruction of a kernel may require more than a few clock cycles to execute (for example, an instruction to read from global memory will require multiple clock cycles). Any instruction that requires multiple clock cycles to execute incurs latency. The latency of long-running instructions can be hidden by executing instructions from other warps while waiting for the result of the previous warp. This technique of filling the latency of expensive operations with work from other threads is often called <strong>latency hiding</strong>.</p>
<span id="Thread_Divergence"><h1>Thread Divergence</h1></span>
<p>It is reasonable to imagine that your CUDA program contains flow-control statements like <strong>if-then-else</strong>, <strong>switch</strong>, <strong>while</strong> loops, or <strong>for</strong> loops.  Whenever you introduce these flow-control statements in your code, you also introduce the possibility of thread divergence.  It is important to be aware of the consequence of thread divergence and also to understand how you can minimize the negative impact of divergence.</p>
<p>Thread divergence occurs when some threads in a warp follow a different execution path than others.  Let&#8217;s take the following code block as an example:</p>
<div class="notranslate">
<pre class="brush:cpp;toolbar:false;first-line:1;" title="test.cu">
__global__ void TestDivergence( float* dst, float* src )
{
    unsigned int index = ( blockDim.x * blockIdx.x ) + threadIdx.x;
    float value = 0.0f;

    if ( threadIdx.x % 2 == 0 )
    {
        // Threads executing PathA are active while threads
        // executing PathB are inactive.
        value = PathA( src );
    }
    else
    {
        // Threads executing PathB are active while threads 
        // executing PathA are inactive.
        value = PathB( src );
    }
    // Threads converge here again and execute in parallel.
    dst[index] = value;
}
</pre>
</div>
<p>Then our flow control and thread divergence would look something like this:</p>
<div id="fig-21" class="wp-caption alignnone" style="width: 1054px"><a href="http://3dgep.com/wp-content/uploads/2011/11/Thread-Divergence.png"><img src="http://3dgep.com/wp-content/uploads/2011/11/Thread-Divergence.png" alt="Thread Divergence" title="Thread Divergence" width="1044" height="437" class="size-full wp-image-2010" /></a><p class="wp-caption-text"><strong>Figure 21.</strong> Thread Divergence</p></div>
<p>As you can see from this example, the even numbered threads in each block will execute <strong>PathA</strong> while the odd numbered threads in the block will execute <strong>PathB</strong>.  This is pretty much the worst-case scenario for simple divergence example.  </p>
<p>Both <strong>PathA</strong> and <strong>PathB</strong> cannot be executed concurrently on all threads because their execution paths are different.  Only the threads that execute the exact same execution path can run concurrently so the total running time of the warp is the sum of the execution time of both <strong>PathA</strong> and <strong>PathB</strong>.</p>
<p>In this example, the threads in the warp that execute <strong>PathA</strong> are activated if the condition is true and all the other threads are deactivated.  Then, in another pass, all the threads that execute <strong>PathB</strong> are activated if the condition is false are activated and the other threads are deactivated.  This means that to resolve this condition requires 2-passes to be executed for a single warp.</p>
<p>The overhead of having the warp execute both <strong>PathA</strong> and <strong>PathB</strong> can be eliminated if the programmer  takes careful consideration when writing the kernel.  If possible, all threads of a block (since warps can&#8217;t span thread blocks) should execute the same execution path.  This way you guarantee that all threads in a warp will execute the same execution path and there will be no thread divergence within a block.</p>
<span id="Memory_Model"><h1>Memory Model</h1></span>
<p>There are several different types of memory that your CUDA application has access to. For each different memory type there are tradeoffs that must be considered when designing the algorithm for your CUDA kernel.</p>
<p>Global memory has a very large address space, but the latency to access this memory type is very high. Shared memory has a very low access latency but the memory address is small compared to Global memory. In order to make proper decisions regarding where to place data and when, you must understand the differences between these memory types and how these decisions will affect the performance of your kernel.</p>
<p>In the next sections, I will describe the different memory types and show examples of using different memory to improve the performance of your kernel.</p>
<span id="CUDA_Memory_Types"><h1>CUDA Memory Types</h1></span>
<p>Every CUDA enabled GPU provides several different types of memory. These different types of memory each have different properties such as access latency, address space, scope, and lifetime.</p>
<p>The different types of memory are <strong>register</strong>, <strong>shared</strong>, <strong>local</strong>, <strong>global</strong>, and <strong>constant</strong> memory.</p>
<p>On devices with compute capability 1.x, there are 2 locations where memory can possibly reside; cache memory and device memory.</p>
<p>The cache memory is considered &#8220;on-chip&#8221; and accesses to the cache is very fast. Shared memory and cached constant memory are stored in cache memory with devices that support compute capability 1.x.</p>
<p>The device memory is considered &#8220;off-chip&#8221; and accesses to device memory is about ~100x slower than accessing cached memory. Global memory, local memory and (uncached) constant memory is stored in device memory.</p>
<p>On devices that support compute capability 2.x, there is an additional memory bank that is stored with each streaming multiprocessor. This is considered L1-cache and although the address space is relatively small, it&#8217;s access latency is very low.</p>
<div id="fig-22" class="wp-caption alignnone" style="width: 589px"><a href="http://3dgep.com/wp-content/uploads/2011/11/CUDA-memory-model.gif"><img src="http://3dgep.com/wp-content/uploads/2011/11/CUDA-memory-model.gif" alt="CUDA Memory Model" title="CUDA Memory Model" width="579" height="641" class="size-full wp-image-2076" /></a><p class="wp-caption-text"><strong>Figure 22.</strong> CUDA Memory Model</p></div>
<p>In the following sections I will describe each type and when it is best to use that memory type.</p>
<span id="Register"><h2>Register</h2></span>
<p>Scalar variables that are declared in the scope of a kernel function and are not decorated with any attribute are stored in register memory by default. Register memory access is very fast, but the number of registers that are available per block is limited.</p>
<p>Arrays that are declared in the kernel function are also stored in register memory but only if access to the array elements are performed using constant indexes (meaning the index that is being used to access an element in the array is not a variable and thus the index can be determined at compile-time). It is currently not possible to perform random access to register variables.</p>
<p>Register variables are private to the thread. Threads in the same block will get private versions of each register variable. Register variables only exists as long as the thread exists. Once the thread finishes execution, a register variable cannot be accessed again. Each invocation of the kernel function must initialize the variable each time it is invoked. This might seem obvious because the scope of the variable is within the kernel function, but this is not true for all variables declared in the kernel function as we will see with shared memory.</p>
<p>Variables declared in register memory can be both read and written inside the kernel. Reads and writes to register memory does not need to be synchronized.</p>
<span id="Local"><h2>Local</h2></span>
<p>Any variable that can&#8217;t fit into the register space allowed for the kernel will spill-over into local memory. Local memory has the same access latency as global memory (that is to say, slow). Accesses to local memory is cached only on GPU&#8217;s with compute capability 2.x or higher<sup><a href="#cite-4">[4]</a></sup>.</p>
<p>Like registers, local memory is private to the thread. Each thread must initialize the contents of a variable stored in local memory before it should be used. You cannot rely on another thread (even in the same block) to initialize local memory because it is private to the thread.</p>
<p>Variables in local memory have the lifetime of the thread. Once the thread is finished executing, the local variable is no longer accessible.</p>
<p>You cannot decorate a variable declaration with any attribute but the compiler will automatically put variable declarations in local memory under the following conditions:</p>
<ul>
<li>Arrays that are accessed with run-time indexes. That is, the compiler can&#8217;t determine the indices at compile time.</li>
<li>Large structures or arrays that would consume too much register space.</li>
<li>Any variable declared that exceeds the number of registers for that kernel (this is called register-spilling).</li>
</ul>
<p>The only way that you can determine if the compiler has put some function scope variables in local memory is by manual inspection of the PTX assembly code (obtained by compiling with the <strong>-ptx</strong> or <strong>-keep</strong> option). Local variables will be declared using the <strong>.local</strong> mnemonic and loaded using the <strong>ld.local</strong> mnemonic and stored with the <strong>st.local</strong> mnemonic.</p>
<p>Variables in local memory can be both read and written within the kernel and access to local memory does not need to be synchronized.</p>
<span id="Shared"><h2>Shared</h2></span>
<p>Variables that are decorated with the <strong>__shared__</strong> attribute are stored in shared memory. Accessing shared memory is very fast (~100 times faster than global memory) although each streaming multiprocessor has a limited amount of shared memory address space.</p>
<p>Shared memory must be declared within the scope of the kernel function but has a lifetime of the block (as opposed to register, or local memory which has a lifetime of the thread). When a block is finished execution, the shared memory that was defined in the kernel cannot be accessed.</p>
<p>Shared memory can be both read from and written to within the kernel. Modification of shared memory must be synchronized unless you guarantee that each thread will only access memory that will not be read-from or written-to by other threads in the block. Block synchronization is acheived using the <strong>__syncthreads()</strong> barrier function inside the kernel function.</p>
<p>Since access to shared memory is faster than accessing global memory, it is more efficient to copy global memory to shared memory to be used within the kernel but only if the number of accesses to global memory can be reduced within the block (as we&#8217;ll see with the matrix multiply example that I will show later).</p>
<span id="Global"><h2>Global</h2></span>
<p>Variables that are decorated with the <strong>__device__</strong> attribute and are declared in global scope (outside of the scope of the kernel function) are stored in global memory. The access latency to global memory is very high (~100 times slower than shared memory) but there is much more global memory than shared memory (up to 6GB but the actual size is different across graphics cards even of the same compute capability).</p>
<p>Unlike register, local, and shared memory, global memory can be read from and written to using the C-function <strong>cudaMemcpy</strong>.</p>
<p>Global memory has a lifetime of the application and is accessible to all threads of all kernels. One must take care when reading from and writing to global memory because thread execution cannot be synchronized across different blocks. The only way to ensure access to global memory is synchronized is by invoking separate kernel invocations (splitting the problem into different kernels and synchronizing on the host between kernel invocations).</p>
<p>Global memory is declared on the host process using <strong>cudaMalloc</strong> and freed in the host process using <strong>cudaFree</strong>. Pointers to global memory can be passed to a kernel function as parameters to the kernel (as we will see in the example later).</p>
<p>Reads from global memory is cached only on devices that support compute capability 2.x or higher<sup><a href="#cite-4">[4]</a></sup> but any write to global memory will invalidate the cache thus eliminating the benefit of cache. Access to global memory on devices that support compute capability 1.x is not cached.</p>
<p>It is a bit of an art-form to reduce the number of accesses to global memory from within a kernel by using blocks of shared memory because the access latency to shared memory is about 100 times faster than accessing global memory. Later, I will show an example of how we can reduce the global memory access using shared memory.</p>
<span id="Constant"><h2>Constant</h2></span>
<p>Variables that are decorated with the <strong>__constant__</strong> attribute are declared in constant memory. Like global variables, constant variables must be declared in global scope (outside the scope of any kernel function). Constant variables share the same memory banks as global memory (device memory) but unlike global memory, there is only a limited amount of constant memory that can be declared (64KB on all compute capabilities).</p>
<p>Access latency to constant memory is considerably faster than global memory because constant memory is cached but unlike global memory, constant memory cannot be written to from within the kernel. This allows constant memory caching to work because we are guaranteed that the values in constant memory will not be changed and therefor will not become invalidated during the execution of a kernel.</p>
<p>Constant memory can be written to by the host process using the <strong>cudaMemcpyToSymbol</strong> function and read-from using the <strong>cudaMemcpyFromSymbol</strong> function. As far as I can tell, it is not possible to dynamically allocate storage for constant memory (the size of constant memory buffers must be statically declared and determined at compile-time).</p>
<p>Like global memory, constant memory has a lifetime of the application. It can be accessed by all threads of all kernels and the value will not change across kernel invocations unless explicitly modified by the host process.</p>
<span id="Properties_of_Memory"><h1>Properties of Memory</h1></span>
<p>The amount of memory that is available to the CUDA application is (in most cases) specific to the compute capability of the device. For each compute capability, the size restrictions of each type of memory (except global memory) id defined in the table below. The application programmer is encouraged to query the device properties in the application using the<br />
<strong>cudaGetDeviceProperties</strong> method.</p>
<table id="table-2" style="width: 100%; border-width: 2px; border-color: #000000; border-style: solid;" border="2" frame="box">
<caption><strong>Table 2.</strong> Memory Compute Capability</caption>
<thead>
<tr style="background-color: #a9a9a9;">
<td style="border-width: 1px; border-color: #000000; border-style: solid;"><strong>Technical Specifications</strong></td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;"><strong>1.0</strong></td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;"><strong>1.1</strong></td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;"><strong>1.2</strong></td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;"><strong>1.3</strong></td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;"><strong>2.x</strong></td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;"><strong>3.0</strong></td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;"><strong>3.5</strong></td>
</tr>
</thead>
<tbody>
<tr>
<td style="border-width: 1px; border-color: #000000; border-style: solid;">Number of 32-bit registers per thread</td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;" colspan="4">128</td>
<td colspan="2" style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">63</td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">255</td>
</tr>
<tr>
<td style="border-width: 1px; border-color: #000000; border-style: solid;">Maximum amount of shared memory per SM</td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;" colspan="4">16 KB</td>
<td colspan="3" style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">48 KB</td>
</tr>
<tr>
<td style="border-width: 1px; border-color: #000000; border-style: solid;">Amount of local memory per thread</td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;" colspan="4" nowrap="nowrap">16 KB</td>
<td colspan="3" nowrap="nowrap" style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;">512 KB</td>
</tr>
<tr>
<td style="border-width: 1px; border-color: #000000; border-style: solid;">Constant memory size</td>
<td style="text-align: center; border-width: 1px; border-color: #000000; border-style: solid;" colspan="7" nowrap="nowrap">64 KB</td>
</tr>
</tbody>
</table>
<p>The following table summarizes the different memory types and the properties of those types.</p>
<table id="table-3" style="width: 100%; border-width: 2px; border-color: #000000; border-style: solid;" border="2" frame="box">
<caption><strong>Table 3.</strong> Properties of Memory Types</caption>
<thead>
<tr style="background-color: #a9a9a9;">
<td style="border-width: 1px; border-color: #000000; border-style: solid;"><strong>Memory</strong></td>
<td style="border-width: 1px; border-color: #000000; border-style: solid;"><strong>Located</strong></td>
<td style="border-width: 1px; border-color: #000000; border-style: solid;"><strong>Cached</strong></td>
<td style="border-width: 1px; border-color: #000000; border-style: solid;"><strong>Access</strong></td>
<td style="border-width: 1px; border-color: #000000; border-style: solid;"><strong>Scope</strong></td>
<td style="border-width: 1px; border-color: #000000; border-style: solid;"><strong>Lifetime</strong></td>
</tr>
</thead>
<tbody>
<tr>
<td style="border-width: 1px; border-color: #000000; border-style: solid;">Register</td>
<td style="border-width: 1px; border-color: #000000; border-style: solid;">cache</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">n/a</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">Host: None<br />
Kernel: R/W</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">thread</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">thread</td>
</tr>
<tr>
<td style="border-width: 1px; border-color: #000000; border-style: solid;">Local</td>
<td style="border-width: 1px; border-color: #000000; border-style: solid;">device</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">1.x: No<br />
2.x: Yes</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">Host: None<br />
Kernel: R/W</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">thread</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">thread</td>
</tr>
<tr>
<td style="border-width: 1px; border-color: #000000; border-style: solid;">Shared</td>
<td style="border-width: 1px; border-color: #000000; border-style: solid;">cache</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">n/a</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">Host: None<br />
Kernel: R/W</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">block</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">block</td>
</tr>
<tr>
<td style="border-width: 1px; border-color: #000000; border-style: solid;">Global</td>
<td style="border-width: 1px; border-color: #000000; border-style: solid;">device</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">1.x: No<br />
2.x: Yes</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">Host: R/W<br />
Kernel: R/W</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">application</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">application</td>
</tr>
<tr>
<td style="border-width: 1px; border-color: #000000; border-style: solid;">Constant</td>
<td style="border-width: 1px; border-color: #000000; border-style: solid;">device</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">Yes</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">Host: R/W<br />
Kernel: R</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">application</td>
<td style="white-space: nowrap; border-width: 1px; border-color: #000000; border-style: solid;">application</td>
</tr>
</tbody>
</table>
<span id="Pointers_to_Memory"><h1>Pointers to Memory</h1></span>
<p>You can use pointers to memory in a kernel but you must be aware that the pointer type does not determine where the memory is located.</p>
<p>For example, the following code declares a pointer to constant memory and a pointer to global memory. You should be aware that only the pointer variable is constant &#8211; not what it points to.</p>
<div class="notranslate">
<pre class="brush:cpp;toolbar:false;first-line:1;" title="test.cu">
__constant__ float* constPtr;
__device__ float* globalPtr;

__global__ void KernelFunction(void)
{
    // Assign the pointer to global memory to a pointer to constant memory.
    // This will not compile because the pointer is constant and you can't change
    // what a const-pointer points to in the kernel.
    constPtr = globalPtr;

    // This will compile because what the const pointer points to is not 
    // necessarily const (if it is, you'll probaly get a runtime error).
    *constPtr = *globalPtr;
}
</pre>
</div>
<p>Since you can&#8217;t dynamically allocate constant memory, this example would not be very useful anyways.</p>
<p>Be careful when using pointers like this. It is a best-practice rule to ensure that a declared pointer only points to one type of memory (so a single pointer declaration will only point to global memory and another pointer declaration will only point to shared memory).  </p>
<span id="Minimize_Global_Memory_Access"><h1>Minimize Global Memory Access</h1></span>
<p>Since access latency is much higher for global memory than it is for shared memory, it should be our objective to minimize accesses to global memory in favor of shared memory. This doesn&#8217;t mean that every access to data in global memory should first be copied into a variable in shared (or register) memory.  Obviously we will not benefit from the low latency shared memory access if our algorithm only needs to make a single access to global memory.  But it happens in some cases that multiple threads in the same block will all read from the same location in global memory.  If this is the case, then we can speed-up our algorithm by first allowing each thread in a block to copy one part of the global memory into a shared memory buffer and then allowing all of the threads in a block to access all elements in that shared memory buffer.</p>
<p>To demonstrate this, I will show several flavors the classic matrix multiply example.  The first example I will show is the standard implementation of the matrix multiply using only global memory access.  Then, I will show an optimized version of the algorithm that uses shared memory to reduce the number of accesses to global memory for threads of the same block.</p>
<span id="Matrix_Multiply_using_Global_Memory"><h2>Matrix Multiply using Global Memory</h2></span>
<p>This version of the matrix multiply algorithm is the easiest to understand however it is also a very naive approach.</p>
<div class="notranslate">
<pre class="brush:cpp;toolbar:false;first-line:1;" title="MatrixMultiply.cu">
__global__ void MatrixMultiplyKernel_GlobalMem( float* C, const float* A, const float* B, unsigned int matrixDim )
{
    // Compute the row index
    unsigned int i = ( blockDim.y * blockIdx.y ) + threadIdx.y;
    // Compute the column index
    unsigned int j = ( blockDim.x * blockIdx.x ) + threadIdx.x;

    unsigned int index = ( i * matrixDim ) + j;
    float sum = 0.0f;
    for ( unsigned int k = 0; k &lt; matrixDim; ++k )
    {
        sum += A[i * matrixDim + k] * B[k * matrixDim + j];
    }
    C[index] = sum;
}
</pre>
</div>
<p>The parameters <strong>A</strong>, <strong>B</strong>, and <strong>C</strong> all point to buffers of global memory.</p>
<p>The fist step is to figure out which row (<strong>i</strong>) and which column (<strong>j</strong>) we are operating on for this kernel.</p>
<p>On line 10, we loop through all of the elements of row <strong>i</strong> of matrix <strong>A</strong> and the column <strong>j</strong> of matrix <strong>B</strong> and compute the summed product of corresponding entries (the dot product of row <strong>i</strong> and column <strong>j</strong>).  A visual aid of this algorithm is shown below.</p>
<div id="fig-23" class="wp-caption alignnone" style="width: 1188px"><a href="http://3dgep.com/wp-content/uploads/2011/11/matrix-multiply1.png"><img src="http://3dgep.com/wp-content/uploads/2011/11/matrix-multiply1.png" alt="Matrix Multiply - Global Memory" title="Matrix Multiply - Global Memory" width="1178" height="1186" class="size-full wp-image-2057" /></a><p class="wp-caption-text"><strong>Figure 23.</strong> Matrix Multiply &#8211; Global Memory</p></div>
<p>If we analyze this algorithm, we may notice that the same row elements of matrix <strong>A</strong> are being accessed for every resulting row element of matrix <strong>C</strong> and all the column elements of matrix <strong>B</strong> are being accessed for every resulting column element of matrix <strong>C</strong>.  If we say that the resulting matrix <strong>C</strong> is <strong>N</strong> x <strong>M</strong> elements, then each element of matrix <strong>A</strong> is being accessed <strong>M</strong> times and each element of matrix <strong>B</strong> is being accessed <strong>N</strong> times. That seems pretty wasteful to me.</p>
<span id="Matrix_Multiply_using_Shared_Memory"><h2>Matrix Multiply using Shared Memory</h2></span>
<p>What if we could reduce the number of times the elements of matrix <strong>A</strong> and <strong>B</strong> are accessed to just 1?  Well, depending on the size of our matrix, we could just store the contents of matrix <strong>A</strong> and matrix <strong>B</strong> into shared memory buffers then just compute the resulting matrix <strong>C</strong> from those buffers instead.  This might work with small matrices (remember that shared memory is local to a single block and with compute capability 1.3, we are limited to matrices of about 20 x 20 because we are limited to 512 threads that can be assigned to a single block).</p>
<p>But what if we had larger matrices to multiply?  If we can find a way to split the problem into &#8220;phases&#8221; then we could simply load each &#8220;phase&#8221; into shared memory, process that &#8220;phase&#8221;, then load the next &#8220;phase&#8221; and process that one until we have exhausted the entire domain.</p>
<p>This technique of splitting our problem domain into phases is called &#8220;tiling&#8221; named because of the way we can visualize the technique as equal sized tiles that represent our problem domain.</p>
<div id="fig-24" class="wp-caption alignnone" style="width: 522px"><a href="http://3dgep.com/wp-content/uploads/2011/11/tiles.jpg"><img src="http://3dgep.com/wp-content/uploads/2011/11/tiles.jpg" alt="Tiles" title="Tiles" width="512" height="512" class="size-full wp-image-2063" /></a><p class="wp-caption-text"><strong>Figure 24.</strong> Tiles</p></div>
<p>For this particular problem, the best partitioning of the problem domain is actually the same as partitioning of the grid of threads that are used to compute the result.</p>
<p>If we split our grid into blocks of 16 x 16 threads (which I showed previously in the section about CUDA thread execution to be a good granularity for this problem) then we can create two buffers in shared memory that are the same size as a single thread block in our kernel grid, one that holds a &#8220;tile&#8221; of matrix <strong>A</strong>, and other to store a &#8220;tile&#8221; of matrix <strong>B</strong>.</p>
<p>Let&#8217;s see how this might look:</p>
<div id="fig-25" class="wp-caption alignnone" style="width: 1289px"><a href="http://3dgep.com/wp-content/uploads/2011/11/matrix-multiply-2.png"><img src="http://3dgep.com/wp-content/uploads/2011/11/matrix-multiply-2.png" alt="Matrix Multiply - Tiles" title="Matrix Multiply - Tiles" width="1279" height="1281" class="size-full wp-image-2065" /></a><p class="wp-caption-text"><strong>Figure 25.</strong> Matrix Multiply &#8211; Tiles</p></div>
<p>So the idea is simple, each thread block defines a pair of shared memory buffers that are used to &#8220;cache&#8221; a &#8220;tile&#8221; of data from matrix <strong>A</strong> and matrix <strong>B</strong>.  Since the &#8220;tile&#8221; is the same size as the thread block, we can just let each thread in the thread block load a single element from matrix <strong>A</strong> into one of the shared memory buffers and a single element from matrix <strong>B</strong> into the other. Using this technique, we can reduce the number of global memory access to <strong>matrixDim / BLOCK_SIZE</strong> per thread (where <strong>BLOCK_SIZE</strong> is the size of the thread block and shared memory buffer in a single dimension).</p>
<p>But will this work?  We only have access to 16 KB (16,384 Bytes) of shared memory per streaming multiprocessor for devices of compute capability 1.x.  If our <strong>BLOCK_SIZE</strong> is 16 then we need 16<sup>2</sup> floating point values (4-bytes each) per shared memory buffer.  So the size in bytes of each shared memory buffer is: </p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?\begin{matrix}bufferSize &#038; = &#038; 16^{2}\cdot4 \\ bufferSize &#038; = &#038; 256\cdot4 \\ bufferSize &#038; = &#038; 1024\end{matrix}" style="float:top;" border="0px" />
<p>And we need 2 buffers, so we will need 2,048 Bytes of shared memory per block.  If you remember from the previous article about the <a href="http://3dgep.com/?p=1913" title="CUDA Thread Execution Model" target="_blank">CUDA thread execution model</a>,<br />
thread blocks of size 16 x 16 will allow 4 resident blocks to be scheduled per streaming multiprocessor.  So 4 blocks each requiring 2,048 Bytes gives a total requirement of 8,192 KB of shared memory which is 50% of the available shared memory per streaming multiprocessor.  So this this tiling strategy will work.</p>
<p>So let&#8217;s see how we might implement this in the kernel.</p>
<div class="notranslate">
<pre class="brush:cpp;toolbar:false;first-line:1;" title="MatrixMultiply.cu">
#define BLOCK_SIZE 16

__global__ void MatrixMultiplyKernel_SharedMem( float* C, const float* A, const float* B, unsigned int matrixDim )
{
    unsigned int tx = threadIdx.x;
    unsigned int ty = threadIdx.y;
    unsigned int bx = blockIdx.x;
    unsigned int by = blockIdx.y;

    // Allocate share memory to store the matrix data in tiles
    __shared__ float sA[BLOCK_SIZE][BLOCK_SIZE];
    __shared__ float sB[BLOCK_SIZE][BLOCK_SIZE];

    // Compute the column index
    unsigned int j = ( blockDim.x * bx ) + tx;
    // Compute the row index
    unsigned int i = ( blockDim.y * by ) + ty;

    unsigned int index = ( i * matrixDim ) + j;
    float sum = 0.0f;

    // Loop through the tiles of the input matrices
    // in separate phases of size BLOCK_SIZE
    for( unsigned int phase = 0; phase &lt; matrixDim/BLOCK_SIZE; ++phase )
    {
        // Allow each thread in the block to populate the shared memory
        sA[ty][tx] = A[i * matrixDim + (phase * BLOCK_SIZE + tx)];
        sB[ty][tx] = B[(phase * BLOCK_SIZE + ty) * matrixDim + j];
        __syncthreads();

        for( unsigned int k = 0; k &lt; BLOCK_SIZE; ++k )
        {
            sum += sA[ty][k] * sB[k][tx];
        }
        __syncthreads();
    }

    C[index] = sum;    
}
</pre>
</div>
<p>On line 5-8, we just store some &#8220;shorthand&#8221; versions of the thread and block indexes into private thread variables (these are stored in registers).</p>
<p>On line 11, and 12 the two shared memory buffers are declared to store enough values that each thread in the thread block can store a single entry in the arrays.</p>
<p>On line 15, the index of the column is computed and stored in another registry variable <strong>j</strong> and on line 16, the row is computed and stored in registry variable <strong>i</strong>.</p>
<p>On line 20, the 1-D index into the result matrix <strong>C</strong> is computed and the sum of the products is stored in the float variable <strong>sum</strong>.</p>
<p>On line 25, we will loop over the &#8220;tiles&#8221; (called phases here) of matrix <strong>A</strong> and matrix <strong>B</strong>.  You should note that this algorithm assumes the size of the matrix is evenly divisible by the size of the thread block.</p>
<p>On lines 28 and 29 is where the magic happens.  Since the shared memory is accessible to every thread in the block, we can let every thread in the block copy 1 element from matrix <strong>A</strong> and one element from matrix <strong>B</strong> into the shared memory blocks.</p>
<p>Before we can access the data in the shared memory blocks, we must ensure that all threads in the entire block have had a chance to write their data.  To do that we need to synchronize the execution of all the threads in the block by calling the <strong>__syncthreads()</strong> method.</p>
<p>Then the <strong>for</strong> loop on line 32 will loop through the elements of shared memory and sum the products.</p>
<p>Before we leave this loop and start filling the next &#8220;tile&#8221; into shared memory, we must ensure that all threads are finished with the shared memory buffers.  To do that, we must execute <strong>__syncthreads()</strong> again on line 36. </p>
<p>This will repeat until all phases (or tiles) of the matrix have been processed.</p>
<p>Once all phases are complete, then the value stored in <strong>sum</strong> will contain the final result and it is written to the destination matrix <strong>C</strong>.</p>
<p>Running the global memory version of the matrix multiply on my laptop with a 512 x 512 matrix runs in about 45 milliseconds.  Running the shared memory version on the same matrix completes in about 15 milliseconds (including copying memory from host to device and copying the result back to host memory).  This provides a speed-up of 300%!</p>
<span id="Resources_as_a_Limiting_Constraint"><h1>Resources as a Limiting Constraint</h1></span>
<p>It is entirely possible to allocate more shared memory per block than 2,048 bytes, but the block scheduler will reduce the number of blocks scheduled on a streaming multiprocessor until the shared memory requirements are met.  If you want to allocate all 16 KB of shared memory in a single block, then only a single block will be resident in the streaming multiprocessor at any given moment which will reduce the occupancy of the streaming multiprocessor to 25% (for a 16 x 16 thread block on compute capability 1.x).</p>
<p>This reduced thread occupancy is not ideal, but it is conceivable to imagine that a single block might have this requirement.  In most cases the GPU will still out-perform the CPU if the benefit of using the low-latency memory is fully realized.</p>
<p>This is also true for the number of registers that can be allocated per block.  If a single kernel declares 32 32-bit variables that must be stored in registers and the thread block consists of 16 x 16 threads, then the maximum number of blocks that can be active in a streaming multiprocessor on a device with compute capability 1.3 is 2 because the maximum number of 32-bit registers that can be used at any moment in time is 16,384.</p>
<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?\begin{matrix}numRegisters &#038; = &#038; 16^{2}\cdot32 \\ numRegisters &#038; = &#038; 256\cdot32 \\ numRegisters &#038; = &#038; 8192\end{matrix}" style="float:top;" border="0px" />
<p>So the number of 32-bit registers/block is 8,192. So the streaming multiprocessor can accommodate a maximum of 8,192 / 16,384 = 2 blocks.</p>
<span id="CUDA_GPU_Occupancy_Calculator"><h1>CUDA GPU Occupancy Calculator</h1></span>
<p>Since version 4.1, the CUDA Toolkit comes with a tool called the <strong>CUDA GPU Occupancy Calculator</strong>. This tool is a Microsoft Excel file that can be used to compute the maximum thread occupancy of the streaming multiprocessor given a set of limiting constraints (threads per block, registers per thread, and shared memory (bytes) per block). This tool is provided in the following folder:</p>
<p><strong>C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\vX.X\tools</strong></p>
<div id="fig-26" class="wp-caption alignnone" style="width: 1204px"><a href="http://3dgep.com/wp-content/uploads/2012/10/CUDA-Occupancy-Calculator.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/CUDA-Occupancy-Calculator.png" alt="CUDA Occupancy Calculator" title="CUDA Occupancy Calculator" width="1194" height="1467" class="size-full wp-image-4271" /></a><p class="wp-caption-text"><strong>Figure 26.</strong> CUDA Occupancy Calculator</p></div>
<p>The <strong>CUDA Occupancy Calculator</strong> allows you to compute the best thread granularity for your thread blocks given a specific compute capability and resource constraints.</p>
<p>You can refer to the second worksheet titled &#8220;Help&#8221; to learn how to use the <strong>CUDA GPU Occupancy Calculator</strong>.</p>
<span id="Exercises"><h1>Exercises</h1></span>
<p><strong>Q1.</strong> Would the <strong>MatrixAddDevice</strong> kernel function shown in this article benefit from the use of <strong>shared memory</strong>? Explain your answer.</p>
<p><strong>A1.</strong> No, it would not benefit from the use of shared memory because each matrix element is only accessed once.  You would still need to access each matrix component to store it in shared memory only to require an access from shared memory to access it again. In this case, store the data in shared memory will only increase the time to execute the kernel because more load/store operations will need to be performed.</p>
<p><strong>Q2.</strong> In almost all of the examples shown here, I decided to use a 16&#215;16 thread granularity for the thread blocks.  Can you explain why this is a good choice for thread granularity on devices of compute capability (you can assume that register use and shared memory allocation are within the limits in each case):</p>
<ol style="list-style-type:lower-latin;">
<li>1.3?</li>
<li>2.0?</li>
<li>3.0?</li>
</ol>
<p><strong>A2.</strong> To answer this question, let&#8217;s take a look at each individual compute capability.</p>
<p><strong>a.</strong> For Compute Capability 1.3 threads are split into groups of <strong>32</strong> threads called <strong>warps</strong>.  The maximum number of warps/SM is <strong>32</strong>. If we create a 16&#215;16 thread block, then we have a total of 256 threads/block.  Each block will be split into 8 warps to be scheduled on the SM.  Since we know that the maximum number of warps/SM for devices with compute capability 1.3 is 32, then <strong>4 thread blocks</strong> will be scheduled on each SM.  Each SM can support up to 8 resident blocks per SM and 4 is still within our limit.  Also with a maximum resident thread limit of <strong>1024 threads</strong> and we exactly meet this requirement (4&#215;256) so we also achieve <strong>100% thread occupancy</strong> on the SM!  So yes, a 16&#215;16 thread block is a good choice for devices with compute capability 1.3.</p>
<p><strong>b.</strong> For devices with compute capability 2.0 threads are also split into groups of <strong>32</strong> threads called <strong>warps</strong>.  In this case, the maximum number of warps/SM is <strong>48</strong>.  Again, we have 256 threads per block which are split into 8 warps to be scheduled on the SM then <strong>6 thread blocks</strong> will be scheduled per SM (48/8). 6 blocks is within the 8 block limit, so we haven&#8217;t exceeded the block limit.  And with a maximum resident thread limit of <strong>1536 threads</strong>, we exactly meet this requirement (6&#215;256) so we also achieve a <strong>100% thread occupancy</strong> on the SM!  So yes, a 16&#215;16 thread block is also a good choice for devices with compute capability 2.0.</p>
<p><strong>c.</strong> For devices with compute capability 3.0 the threads are also split into groups of <strong>32</strong> threads called <strong>warps</strong>.  So again, each block will be split into 8 warps.  The maximum number of warps that can be active in a SM is <strong>64</strong>.  This allows for <strong>8 thread blocks</strong> to be scheduled per SM.  This is within the limit of 16 blocks/SM and again matches exactly the maximum number of threads of <strong>2048 threads</strong> (8&#215;256) that can be scheduled for each SM so we also achieve <strong>100%</strong> thread occupancy. So yes, a 16&#215;16 thread block is also a good choice for devices with compute capability 3.0 (and consequently this is also true for devices of compute capability 3.5).</p>
<p><strong>Q3.</strong> Assuming we have a block of 256 threads each, what is the maximum amount of shared memory we can use per block and still maintain 100% thread occupancy for devices of compute capability (assume the register count is not a limiting resource):</p>
<ol style="list-style-type:lower-latin;">
<li>1.3?</li>
<li>2.0?</li>
<li>3.0?</li>
</ol>
<p><strong>a.</strong> In the previous exercise we already established that with a thread blocks of 256 threads, we will have 4 resident blocks per SM. Since devices of compute capability 1.3 have a maximum <strong>16 KB (16,384 bytes)</strong> of shared memory then each block can use a maximum of <strong>4,096 bytes</strong> (16,384/4) of shared memory while still maintaining 100% thread occupancy.</p>
<p><strong>b.</strong> In the previous exercise we saw that we could schedule 6 blocks of 256 threads. Devices of compute capability 2.0 have a maximum of <strong>48 KB (49,152 bytes)</strong> of shared memory per SM.  This means that we can allocate a maximum of <strong>8,192 bytes</strong> (49,152/6) of shared memory while still maintaining 100% thread occupancy.</p>
<p><strong>c.</strong> In the previous exercise we saw that we could schedule 8 blocks of 256 threads to get 100% thread occupancy.  Devices with compute capability 3.0 also have a maximum of <strong>48 KB (49,152 KB)</strong> of shared memory per SM.  In this case, we can only allocate <strong>6,144 bytes</strong> (49,152/8) of shared memory while still maintaining 100% thread occupancy. </p>
<p><strong>Q4.</strong> In the case (c) above, what would happen if we created thread blocks of 1024 threads?  Would we still have 100% thread occupancy? How much shared memory could we allocate per thread block and maintain 100% thread occupancy?  Explain your answer.</p>
<p><strong>Q5.</strong> Answer question (3) and (4) again but this time compute the number of registers you have available <strong>per thread</strong> while still maintaining 100% thread occupancy. In this case, you can assume that shared memory is not a limiting resource.</p>
<p><strong>Hint:</strong> To answer Q5 correctly, you must also take the register allocation granularity and unit size into consideration.  For compute capability 1.3, the register allocation granularity is at the <strong>block</strong> level and the register allocation unit size is <strong>512</strong>. For compute capability 2.x register allocation granularity is at the <strong>warp</strong> level and the register allocation unit size is <strong>64</strong>.  For compute capability 3.x, the register allocation granularity is at the <strong>warp</strong> level and the register allocation unit size is <strong>256</strong>.</p>
<span id="References"><h1>References</h1></span>
<p><span id="cite-1">1. NVIDIA Corporation (2012, October). <em>CUDA C Programming Guide</em>. (PG-02829-001_v5.0). USA. Available from: <a href="http://docs.nvidia.com/cuda/pdf/CUDA_C_Programming_Guide.pdf" title="CUDA C Programming Guide" target="_blank">http://docs.nvidia.com/cuda/pdf/CUDA_C_Programming_Guide.pdf</a>. Accessed: October 2012.<br />
</span></p>
<p><span id="cite-2">2. NVIDIA Corporation (2012, October). <em>NVIDIA’s Next Generation CUDA Compute Architecture: Kepler GK110</em>. (V1.0). USA. Available from: <a href="http://www.nvidia.com/content/PDF/kepler/NVIDIA-Kepler-GK110-Architecture-Whitepaper.pdf" title="NVIDIA's Next Generation CUDA Compute Architecture: Kepler GK110" target="_blank">http://www.nvidia.com/content/PDF/kepler/NVIDIA-Kepler-GK110-Architecture-Whitepaper.pdf</a>. Accessed: October 2012.</span></p>
<p><span id="cite-3">3. NVIDIA Corporation (2012, October). <em>NVIDIA CUDA Getting Started Guide For Microsoft Windows</em>. (DU-05349-001_v5.0). USA. Available from: <a href="http://developer.download.nvidia.com/compute/cuda/5_0/rel/docs/CUDA_Getting_Started_Guide_For_Microsoft_Windows.pdf" title="NVIDIA CUDA Getting Started Guide For Microsoft Windows" target="_blank">http://developer.download.nvidia.com/compute/cuda/5_0/rel/docs/CUDA_Getting_Started_Guide_For_Microsoft_Windows.pdf</a>. Accessed: October 2012.<br />
</span></p>
<p><span id="cite-4">4. NVIDIA Corporation (2012, October). <em>CUDA C Best Practices Guide</em>. (DG-05603-001_v5.0). USA. Available from: <a href="http://docs.nvidia.com/cuda/pdf/CUDA_C_Best_Practices_Guide.pdf" title="CUDA C Best Practices Guide" target="_blank">http://docs.nvidia.com/cuda/pdf/CUDA_C_Best_Practices_Guide.pdf</a>. Accessed: October 2012.</span></p>
<p><span id="cite-5">5. Kirk, David B. and Hwu, Wen-mei W. (2010). <em>Programming Massively Parallel Processors</em>. 1st. ed. Burlington, MA 01803, USA: Morgan Kaufmann Publishers.</span></p>
]]></content:encoded>
			<wfw:commentRss>http://3dgep.com/?feed=rss2&#038;p=4151</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Physics in Unity 3.5</title>
		<link>http://3dgep.com/?p=4027</link>
		<comments>http://3dgep.com/?p=4027#comments</comments>
		<pubDate>Mon, 01 Oct 2012 15:55:05 +0000</pubDate>
		<dc:creator>Jeremiah van Oosten</dc:creator>
				<category><![CDATA[Unity]]></category>
		<category><![CDATA[Bounce]]></category>
		<category><![CDATA[Bouncyness]]></category>
		<category><![CDATA[Collider]]></category>
		<category><![CDATA[Dynamic Friction]]></category>
		<category><![CDATA[engine]]></category>
		<category><![CDATA[Friction]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[Kinematic]]></category>
		<category><![CDATA[OnColliderEnter]]></category>
		<category><![CDATA[OnColliderExit]]></category>
		<category><![CDATA[OnColliderStay]]></category>
		<category><![CDATA[OnTriggerEnter]]></category>
		<category><![CDATA[OnTriggerExit]]></category>
		<category><![CDATA[OnTriggerStay]]></category>
		<category><![CDATA[Physic Material]]></category>
		<category><![CDATA[physics]]></category>
		<category><![CDATA[Physics Engine]]></category>
		<category><![CDATA[Rigidbody]]></category>
		<category><![CDATA[Rigidbody Collider]]></category>
		<category><![CDATA[Static Collider]]></category>
		<category><![CDATA[Static Friction]]></category>
		<category><![CDATA[Trigger Collider]]></category>

		<guid isPermaLink="false">http://3dgep.com/?p=4027</guid>
		<description><![CDATA[In this article, I will introduce the reader to the Physics system used in the Unity game engine.  I will talk about Physic Materials, Colliders, Rigidbodies, Character Controller, and Joints. <a href="http://3dgep.com/?p=4027">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<style type="text/css">
.table_cell_text {
	color: #FFF;
	text-align: center;
	font-weight: bold;
	background-color: #666;
}
</style>
<div id="attachment_4154" class="wp-caption alignleft" style="width: 160px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Physics-in-Unity-Thumb.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Physics-in-Unity-Thumb-150x150.png" alt="Physics in Unity" title="Physics in Unity" width="150" height="150" class="size-thumbnail wp-image-4154" /></a><p class="wp-caption-text">Physics in Unity</p></div>
<p>In this article, I will introduce the reader to the Physics system used in the Unity game engine.  First, I will introduce the <strong>Physic Material</strong> Asset that is used to define physics properties for collider surfaces.  I will also introduce <strong>Colliders</strong> and talk about the different kinds of <strong>Collider</strong> types you can create. The <strong>Rigidbody</strong> component is absolutely essential for performing physics simulations on GameObjects. I will show you how you can create a Rigidbody GameObject that can be user controlled.  I will also talk about the <strong>Character Controller</strong> component that is provided by Unity to control upright characters.  And finally, I will introduce the different <strong>Joints</strong> that are available in Unity.</p>
<p><span id="more-4027"></span></p>
<div style="clear: both;"><div class='toc wptoc'>
<h2>Table of Contents</h2>
<ol class='toc-odd level-1'>
	<li>
		<a href="#Introduction">Introduction</a>
	</li>
	<li>
		<a href="#Physics_Material">Physics Material</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Frictionless_Physic_Material">Frictionless Physic Material</a>
			</li>
		</ol>
	<li>
		<a href="#Colliders">Colliders</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Trigger_Collider">Trigger Collider</a>
			</li>
			<li>
				<a href="#Static_Collider">Static Collider</a>
			</li>
			<li>
				<a href="#Rigidbody_Collider">Rigidbody Collider</a>
			</li>
			<li>
				<a href="#Kinematic_Rigidbody_Collider">Kinematic Rigidbody Collider</a>
			</li>
			<li>
				<a href="#Collision_Matrix">Collision Matrix</a>
			</li>
			<li>
				<a href="#Trigger_Matrix">Trigger Matrix</a>
			</li>
			<li>
				<a href="#Box_Collider">Box Collider</a>
			</li>
			<li>
				<a href="#Sphere_Collider">Sphere Collider</a>
			</li>
			<li>
				<a href="#Capsule_Collider">Capsule Collider</a>
			</li>
			<li>
				<a href="#Mesh_Collider">Mesh Collider</a>
			</li>
			<li>
				<a href="#Compound_Colliders">Compound Colliders</a>
			</li>
		</ol>
	<li>
		<a href="#Rigidbodies">Rigidbodies</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Physics_Rigidbody">Physics Rigidbody</a>
			</li>
			<li>
				<a href="#Kinematic_Rigidbody">Kinematic Rigidbody</a>
			</li>
			<li>
				<a href="#Properties_of_a_Rigidbody">Properties of a Rigidbody</a>
			</li>
			<li>
				<a href="#Rigidbody_Tutorial">Rigidbody Tutorial</a>
				<ol class='toc-odd level-3'>
					<li>
						<a href="#Create_a_New_Scene">Create a New Scene</a>
					</li>
					<li>
						<a href="#Create_a_Plane">Create a Plane</a>
					</li>
					<li>
						<a href="#Create_a_Rigidbody_Collider">Create a Rigidbody Collider</a>
					</li>
					<li>
						<a href="#Create_a_Static_Collider">Create a Static Collider</a>
					</li>
					<li>
						<a href="#Create_a_Trigger_Collider">Create a Trigger Collider</a>
					</li>
					<li>
						<a href="#Trigger_Script">Trigger Script</a>
					</li>
					<li>
						<a href="#Create_a_Controllable_Rigidbody">Create a Controllable Rigidbody</a>
					</li>
				</ol>
</ol>
			<li>
				<a href="#Character_Controller">Character Controller</a>
				<ol class='toc-even level-2'>
					<li>
						<a href="#Character_Controller_Tutorial">Character Controller Tutorial</a>
						<ol class='toc-odd level-3'>
							<li>
								<a href="#Create_a_New_Scene_1">Create a New Scene</a>
							</li>
							<li>
								<a href="#Add_a_Character_Controller">Add a Character Controller</a>
							</li>
							<li>
								<a href="#Character_Controller_Push_Script">Character Controller Push Script</a>
							</li>
							<li>
								<a href="#Try_This...">Try This...</a>
							</li>
						</ol>
</ol>
					<li>
						<a href="#Joints">Joints</a>
						<ol class='toc-even level-2'>
							<li>
								<a href="#Hinge_Joint">Hinge Joint</a>
							</li>
							<li>
								<a href="#Spring_Joint">Spring Joint</a>
							</li>
							<li>
								<a href="#Fixed_Joint">Fixed Joint</a>
							</li>
							<li>
								<a href="#Character_Joint">Character Joint</a>
							</li>
						</ol>
					<li>
						<a href="#Conclusion">Conclusion</a>
					</li>
					<li>
						<a href="#References">References</a>
					</li>
</ol>
</div>
<div class='wptoc-end'>&nbsp;</div></div>
<span id="Introduction"><h1>Introduction</h1></span>
<p>There is nothing real or natural about how things behave in computer games. They don&#8217;t know anything about the natural physical phenomenon that exists in reality.  If you place a bunch of objects in a scene in Unity, these objects will not naturally know what they are supposed to do. They won&#8217;t even be affected by gravity unless you explicitly tell them what gravity is.  Game engines (like Unity) require Physics to be simulated using a <strong>Physics Engine</strong>.  The Physics Engine tries to simulate physics in your game so that the objects in your game demonstrate natural physical phenomenon.</p>
<p>Physics components in Unity are split into several categories:</p>
<ul>
<li><strong>Physics Material</strong>: The <strong>Physic Material</strong> is an <strong>Asset</strong> type that describes how a physically controlled object reacts to other physically controlled objects.</li>
<li><strong>Collider</strong>: The <strong>Collider</strong> components are used to describe the collision shape of an object.</li>
<li><strong>Rigidbody</strong>: The <strong>Rigidbody</strong> component is required to allow your GameObject to be controlled by the physics engine and influence other physics controlled objects.</li>
<li><strong>Character Controller</strong>: The <strong>Character Controller</strong> component is most commonly used on up-right character models. It&#8217;s used to move the character around the scene without a <strong>Rigidbody</strong> attached to the GameObject but still performs collision detection on other colliders in your scene.</li>
<li><strong>Cloth</strong>: Unity provides a few components that can be used to simulate cloth behavior in your game. This is useful for capes or dresses, or simulating flags or banners.</li>
<li><strong>Joints</strong>: <strong>Joints</strong> allow you to define a constraint between two <strong>Rigidbodies</strong>.  This is useful for hinges or creating springs between two objects.</li>
</ul>
<p>In this article, I will introduce you to the physics system in Unity and give you an idea of how it works so that you can implement your physics controlled objects correctly in your own games.</p>
<span id="Physics_Material"><h1>Physics Material</h1></span>
<p>The <strong>Physic Material</strong> is an <strong>Asset</strong> type that can be assigned to <strong>Colliders</strong>.  The <strong>Physic Material</strong> describes both the friction and bounciness of a physics controlled object.</p>
<div id="attachment_4071" class="wp-caption alignnone" style="width: 286px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Physic-Material.gif"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Physic-Material.gif" alt="Unity - Physic Material" title="Unity - Physic Material" width="276" height="374" class="size-full wp-image-4071" /></a><p class="wp-caption-text">Unity &#8211; Physic Material</p></div>
<p>The <strong>Physic Material</strong> has the following properties:</p>
<ul>
<li><strong>Dynamic Friction</strong>: The <strong>Dynamic Friction</strong> property determines the friction that is applied while the object is in motion.  This property usually has a value in the range <strong>0</strong> to <strong>1</strong>.  A value of <strong>0</strong> will cause no friction to be applied to the surface and a value of <strong>1</strong> will cause the object to slow down very quickly when it is in contact with another surface.</li>
<li><strong>Static Friction</strong>: The <strong>Static Friction</strong> property determines the friction that is applied while the object is not moving.  A value of <strong>0</strong> will allow the object to start moving very easily. A value of <strong>1</strong> will take a lot of force to get the object to start moving.</li>
<li><strong>Bounciness</strong>: Determines how much the object will bounce when it hits another collider.  With a value of <strong>0</strong>, the object will not bounce at all (all kinetic energy will be absorbed). With a value of <strong>1</strong>, the object will bounce indefinitely (all kinetic energy will be maintained). With a value greater than <strong>1</strong> will cause the object to bounce higher (it will gain kinetic energy).</li>
<li><strong>Friction Combine</strong>: Determines how the friction of the two colliding objects is combined:
<ul>
<li><strong>Average</strong>: The applied friction is the average friction between the two colliders.</li>
<li><strong>Multiply</strong>: The applied friction is the product of the friction of both colliders.</li>
<li><strong>Minimum</strong>: The applied friction is the minimum friction of either collider.</li>
<li><strong>Maximum</strong>: The applied friction is the maximum friction of either collider.</li>
</ul>
</li>
<li><strong>Bounce Combine</strong>: Determines how the bounciness of the two colliding objects is combined:
<ul>
<li><strong>Average</strong>: The applied bounciness is the average bounciness between the two colliders.</li>
<li><strong>Multiply</strong>: The applied bounciness is the product of the bounciness of both colliders.</li>
<li><strong>Minimum</strong>: The applied bounciness is the minimum bounciness of either collider.</li>
<li><strong>Maximum</strong>: The applied bounciness is the maximum bounciness of either collider.</li>
</ul>
</li>
<li><strong>Friction Direction 2</strong>: The <strong>Friction Direction 2</strong> is a vector in object local space that can be used to simulate surfaces that can slide easier in one direction than in the other.  For example, a corrugated surface that can slide easily in the direction of the corrugated grooves, but tend to resist motion opposite to the corrugated groves.</li>
<li><strong>Dynamic Friction 2</strong>: The amount of dynamic friction to apply in the direction of <strong>Friction Direction 2</strong> while the object is in motion.</li>
<li><strong>Static Friction 2</strong>: The ammount of static friction to apply in the direction of <strong>Friction Direction 2</strong> while the object is at rest.</li>
</ul>
<p>Unity provides a few default <strong>Physic Materials</strong> in the standard packages for Ice, Metal, Rubber, and Wood.</p>
<span id="Frictionless_Physic_Material"><h2>Frictionless Physic Material</h2></span>
<p>To create a completely friction-less material, create a new <strong>Physic Material</strong> asset in the <strong>Project</strong> view and set it&#8217;s properties to the following values:</p>
<ul>
<li><strong>Dynamic Friction</strong>: 0</li>
<li><strong>Static Friction</strong>: 0</li>
<li><strong>Friction Combine</strong>: Minimum</li>
</ul>
<p>Leave the other properties as their defaults.</p>
<p>The <strong>Bounciness</strong> properties don&#8217;t effect friction, so you can set them to anything you want.</p>
<p>We&#8217;ll use this frictionless <strong>Physic Material</strong> later when we start playing with <strong>Rigidbody</strong> components.</p>
<span id="Colliders"><h1>Colliders</h1></span>
<p><strong>Colliders</strong> are used to define the collision shape of objects in your scene. Unity provides three primitive collider types: <strong>Box</strong>, <strong>Sphere</strong> and <strong>Capsule</strong>.  Unity also provides a <strong>Mesh Collider</strong> component that can be used to represent a simplified version of your complex meshes.  For vehicles, Unity also provides a <strong>Wheel Collider</strong> component and a <strong>Terrain Collider</strong> component that can be used on terrains.</p>
<span id="Trigger_Collider"><h2>Trigger Collider</h2></span>
<p>Any <strong>Collider</strong> type (<strong>Box</strong>, <strong>Sphere</strong>, <strong>Capsule</strong>, <strong>Mesh</strong>, and <strong>Terrain</strong>) can be used as a <strong>Trigger</strong> by setting the <strong>Is Trigger</strong> property to <strong>true</strong>.  If the <strong>Collider</strong> is a <strong>Trigger</strong> we call it a <strong>Trigger Collider</strong>. <strong>Trigger Colliders</strong> will not participate in physics simulations but they will fire the <strong>OnTriggerEnter</strong>, <strong>OnTriggerStay</strong>, and <strong>OnTriggerExit</strong> events on the GameObject they are attached to as long as the collider that intersected with the trigger is a <strong>Rigidbody Collider</strong> (see below).</p>
<p>If you place a <strong>Rigidbody</strong> on a <strong>Trigger Collider</strong>, it will be effected by gravity (if the <strong>Use Gravity</strong> property is true on the <strong>Rigidbody</strong> component) but it will not collide with other colliders in your scene.  If you have <strong>Rigidbody</strong> objects in your scene that are falling through the floor, make sure the collider component does not have the <strong>Is Trigger</strong> property set to true.</p>
<p><strong>Trigger Colliders</strong> can be used for many different things. You can place a <strong>Trigger Collider</strong> near a doorway that opens the door when the player enters the collider and closes the door when the user exits the <strong>Trigger Collider</strong>.</p>
<div id="attachment_4032" class="wp-caption alignnone" style="width: 739px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Trigger-Collider.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Trigger-Collider.png" alt="Unity - Trigger Collider" title="Unity - Trigger Collider" width="729" height="647" class="size-full wp-image-4032" /></a><p class="wp-caption-text">Unity &#8211; Trigger Collider</p></div>
<p>In the image above, we see a screenshot from the game AngryBots that ships with Unity 3.5. The green box centered on the door is used to play the door opening animation when the player enters the trigger area and plays the door opening animation in reverse when the player exits the trigger area.</p>
<span id="Static_Collider"><h2>Static Collider</h2></span>
<p>A <strong>Static Collider</strong> is any non-trigger <strong>Collider</strong> without a <strong>Rigidbody</strong> component.  Without a <strong>Rigidbody</strong> component, an object will not be influenced by physics.  <strong>Static Colliders</strong> can be used to block GameObjects with <strong>Rigidbody</strong> components but no matter how hard another <strong>Rigidbody</strong> component hits a <strong>Static Collider</strong>, the <strong>Static Collider</strong> will not move.  <strong>Static Colliders</strong> are ideal for the walls, floors, and other fixed (static) level decoration in your scene.</p>
<span id="Rigidbody_Collider"><h2>Rigidbody Collider</h2></span>
<p>A <strong>Rigidbody Collider</strong> on the other hand, is a <strong>Collider</strong> with a <strong>Rigidbody</strong> component.  <strong>Rigidbody Colliders</strong> will be simulated by physics and they will collide with other <strong>Static Colliders</strong> and <strong>Rigidbody Colliders</strong>.  They will not collide with (be blocked by) <strong>Trigger Colliders</strong> but they will receive the <strong>OnTriggerEnter</strong>, <strong>OnTriggerStay</strong>, and <strong>OnTriggerExit</strong> events if they move into the area defined by the <strong>Trigger Collider</strong>.</p>
<span id="Kinematic_Rigidbody_Collider"><h2>Kinematic Rigidbody Collider</h2></span>
<p>A <strong>Kinematic Rigidbody Collider</strong> is a <strong>Rigidbody Collider</strong> with the <strong>Is Kinematic</strong> flag set to <strong>true</strong> on the <strong>Rigidbody</strong> component.  <strong>Kinematic Rigidbody Colliders</strong> will not be influenced by physics and they must be moved using the GameObject&#8217;s <strong>Transform</strong> component (using the <strong>transform.position</strong> and <strong>transform.rotation</strong>).  <strong>Kinematic Rigidbody Colliders</strong> are commonly used on animated characters. While the character is animated, the <strong>Rigidbody</strong> component will be <strong>kinematic</strong> but if you want to switch the character to a <strong>Ragdoll</strong> state, you will disable the <strong>Is Kinematic</strong> flag and the character will act like a limp doll and fall to the floor.</p>
<p><strong>Kinematic Rigidbody Colliders</strong> will only collide with other <strong>Rigidbody Colliders</strong>.  <strong>Kinematic Rigidbody Colliders</strong> will push other <strong>Rigidbody Colliders</strong> but they will not react to being pushed by other <strong>Rigidbody Colliders</strong>.</p>
<p><strong>Kinematic Rigidbody Colliders</strong> will not collide with <strong>Static Colliders</strong>.</p>
<span id="Collision_Matrix"><h2>Collision Matrix</h2></span>
<p>The following table shows which collider types will perform collision detection.  The <strong>OnCollisionEnter()</strong>, <strong>OnCollisionStay()</strong>, and <strong>OnCollisionExit()</strong> messages will also be sent on GameObjects that meet the collision requirements.  Also keep in mind that only colliders that also have a <strong>Rigidbody</strong> will react to collisions, that is, they will be pushed by other <strong>Rigidbody</strong> colliders.</p>
<table border="2">
<tbody>
<tr>
<th align="center" colspan="7"><strong>Collision detection occurs and messages are sent upon collision</strong></th>
</tr>
<tr>
<td nowrap="nowrap"><strong> </strong></td>
<td align="left"><strong>Static Collider</strong></td>
<td align="left"><strong>Rigidbody Collider</strong></td>
<td align="left"><strong>Kinematic Rigidbody Collider</strong></td>
<td align="left"><strong>Static Trigger Collider</strong></td>
<td align="left"><strong>Rigidbody Trigger Collider</strong></td>
<td align="left"><strong>Kinematic Rigidbody Trigger Collider</strong></td>
</tr>
<tr>
<td align="left" nowrap="nowrap"><strong>Static Collider</strong></td>
<td> </td>
<td align="center" valign="middle" bgcolor="#666666" class="table_cell_text"><strong>Yes</strong></td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td align="left" nowrap="nowrap"><strong>Rigidbody Collider</strong></td>
<td align="center" valign="middle" bgcolor="#666666" class="table_cell_text"><strong>Yes</strong></td>
<td align="center" valign="middle" bgcolor="#666666" class="table_cell_text"><strong>Yes</strong></td>
<td align="center" valign="middle" bgcolor="#666666" class="table_cell_text"><strong>Yes</strong></td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td align="left" nowrap="nowrap"><strong>Kinematic Rigidbody Collider</strong></td>
<td> </td>
<td align="center" valign="middle" bgcolor="#666666" class="table_cell_text"><strong>Yes</strong></td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td align="left" nowrap="nowrap"><strong>Static Trigger Collider</strong></td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td align="left" nowrap="nowrap"><strong>Rigidbody Trigger Collider</strong></td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td align="left" nowrap="nowrap"><strong>Kinematic Rigidbody Trigger Collider</strong></td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-BoxCollider.html" title="Unity - Box Collider" target="_blank">Source</a>]</p>
<span id="Trigger_Matrix"><h2>Trigger Matrix</h2></span>
<p>The following table shows which collider types will fire <strong>Trigger</strong> events. The <strong>OnTriggerEnter()</strong>, <strong>OnTriggerStay()</strong>, and <strong>OnTriggerExit()</strong> events will also be called on colliders that meet the trigger requirements.  Keep in mind that trigger events will only be called on <strong>Trigger Colliders</strong>.</p>
<table border="2">
<tbody>
<tr>
<th align="center" colspan="7"><strong>Trigger messages are sent upon collision</strong></th>
</tr>
<tr>
<td><strong> </strong></td>
<td align="left"><strong>Static Collider</strong></td>
<td align="left"><strong>Rigidbody Collider</strong></td>
<td align="left"><strong>Kinematic Rigidbody Collider</strong></td>
<td align="left"><strong>Static Trigger Collider</strong></td>
<td align="left"><strong>Rigidbody Trigger Collider</strong></td>
<td align="left"><strong>Kinematic Rigidbody Trigger Collider</strong></td>
</tr>
<tr>
<td align="left" nowrap="nowrap"><strong>Static Collider</strong></td>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
</tr>
<tr>
<td align="left" nowrap="nowrap"><strong>Rigidbody Collider</strong></td>
<td> </td>
<td> </td>
<td> </td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
</tr>
<tr>
<td align="left" nowrap="nowrap"><strong>Kinematic Rigidbody Collider</strong></td>
<td> </td>
<td> </td>
<td> </td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
</tr>
<tr>
<td align="left" nowrap="nowrap"><strong>Static Trigger Collider</strong></td>
<td> </td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
<td> </td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
</tr>
<tr>
<td align="left" nowrap="nowrap"><strong>Rigidbody Trigger Collider</strong></td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
</tr>
<tr>
<td align="left" nowrap="nowrap"><strong>Kinematic Rigidbody Trigger Collider</strong></td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
<td align="center" class="table_cell_text">Yes</td>
</tr>
</tbody>
</table>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-BoxCollider.html" title="Unity - Box Collider" target="_blank">Source</a>]</p>
<span id="Box_Collider"><h2>Box Collider</h2></span>
<p>The <strong>Box Collider</strong> is a basic cube-shaped collision primitive.  It is commonly used to mimic the shape of cube like objects such as crates and boxes, the hull of a car, walls, doors, tables, and other level geometry that resembles the shape of a cube.</p>
<div id="attachment_3691" class="wp-caption alignnone" style="width: 699px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Box-Collider.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Box-Collider.png" alt="Unity - Box Collider" title="Unity - Box Collider" width="689" height="399" class="size-full wp-image-3691" /></a><p class="wp-caption-text">Unity &#8211; Box Collider</p></div>
<p>The <strong>Box Collider</strong> is also a very common primitive collider that is used to create triggers in your game (as shown in the Angry Bots screenshot above).</p>
<p>The Box Collider has the following properties:</p>
<div id="attachment_4059" class="wp-caption alignnone" style="width: 339px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Box-Collider-Properties.gif"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Box-Collider-Properties.gif" alt="Unity - Box Collider Properties" title="Unity - Box Collider Properties" width="329" height="359" class="size-full wp-image-4059" /></a><p class="wp-caption-text">Unity &#8211; Box Collider Properties</p></div>
<ul>
<li><strong>Is Trigger</strong>: If <strong>true</strong>, this collider will be considered a <strong>Trigger Collider</strong> and will no longer be influenced by physics but it will fire <strong>Trigger</strong> events on other <strong>Rigidbody</strong> colliders.</li>
<li><strong>Material</strong>: The <strong>Physics Material</strong> that determines the friction and bounce of this object. The <strong>Physics Material</strong> is irrelevant if this is a <strong>Trigger Collider</strong>.
<li><strong>Center</strong>: The <strong>X</strong>, <strong>Y</strong>, <strong>Z</strong>, position of the <strong>Collider</strong> relative to the GameObject&#8217;s <strong>Transform</strong>.
<li><strong>Size</strong>: The scale of the collider relative to the GameObjects&#8217;s scale.
</li>
</ul>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-BoxCollider.html" title="Unity - Box Collider" target="_blank">Source</a>]</p>
<span id="Sphere_Collider"><h2>Sphere Collider</h2></span>
<p>The <strong>Sphere Collider</strong> is similar to a Box Collider except it resembles the shape of a sphere instead of a cube.</p>
<div id="attachment_4061" class="wp-caption alignnone" style="width: 652px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Sphere-Collider-Properties.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Sphere-Collider-Properties.png" alt="Unity - Sphere Collider Properties" title="Unity - Sphere Collider Properties" width="642" height="457" class="size-full wp-image-4061" /></a><p class="wp-caption-text">Unity &#8211; Sphere Collider Properties</p></div>
<p>The <strong>Sphere Collider</strong> has the following properties:</p>
<ul>
<li><strong>Is Trigger</strong>: If <strong>true</strong>, this collider will be considered a <strong>Trigger Collider</strong> and will no longer be influenced by physics but it will fire <strong>Trigger</strong> events on other <strong>Rigidbody</strong> colliders.</li>
<li><strong>Material</strong>: The <strong>Physics Material</strong> that determines the friction and bounce of this object. The <strong>Physics Material</strong> is irrelevant if this is a <strong>Trigger Collider</strong>.
<li><strong>Center</strong>: The <strong>X</strong>, <strong>Y</strong>, <strong>Z</strong>, position of the <strong>Collider</strong> relative to the GameObject&#8217;s position.
<li><strong>Radius</strong>: The radius of the collider relative to the GameObjects&#8217;s scale.
</li>
</ul>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-SphereCollider.html" title="Sphere Collider" target="_blank">Source</a>]</p>
<span id="Capsule_Collider"><h2>Capsule Collider</h2></span>
<p>The <strong>Capsule Collider</strong> resembles the shape of a capsule. It is most commonly used to approximate the size and shape of a character.  The <strong>Capsule Collider</strong> is also commonly used on the bones of an animated character.  When the character is hit by something, the capsule colliders can be switched from kinematic to physics controlled so the character falls to the floor like a ragdoll.</p>
<div id="attachment_4063" class="wp-caption alignnone" style="width: 765px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Ragdoll.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Ragdoll.png" alt="Unity - Ragdoll" title="Unity - Ragdoll" width="755" height="679" class="size-full wp-image-4063" /></a><p class="wp-caption-text">Unity &#8211; Ragdoll</p></div>
<div id="attachment_4065" class="wp-caption alignnone" style="width: 765px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Capsule-Collider-Properties.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Capsule-Collider-Properties.png" alt="Unity - Capsule Collider Properties" title="Unity - Capsule Collider Properties" width="755" height="495" class="size-full wp-image-4065" /></a><p class="wp-caption-text">Unity &#8211; Capsule Collider Properties</p></div>
<p>The <strong>Capsule Collider</strong> has the following properties:</p>
<ul>
<li><strong>Is Trigger</strong>: If <strong>true</strong>, this collider will be considered a <strong>Trigger Collider</strong> and will no longer be influenced by physics but it will fire <strong>Trigger</strong> events on other <strong>Rigidbody</strong> colliders.</li>
<li><strong>Material</strong>: The <strong>Physics Material</strong> that determines the friction and bounce of this object. The <strong>Physics Material</strong> is irrelevant if this is a <strong>Trigger Collider</strong>.
<li><strong>Center</strong>: The <strong>X</strong>, <strong>Y</strong>, <strong>Z</strong>, position of the <strong>Collider</strong> relative to the GameObject&#8217;s position.
<li><strong>Radius</strong>: The radius of the capsule&#8217;s body.
</li>
<li><strong>Height</strong>: The length of the capsule body.</li>
<li><strong>Direction</strong>: The axis of the capsule&#8217;s lengthwise orientation relative to the the GameObject&#8217;s local space.</li>
</ul>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-CapsuleCollider.html" title="Capsule Collider" target="_blank">Source</a>]</p>
<span id="Mesh_Collider"><h2>Mesh Collider</h2></span>
<p>The <strong>Mesh Collider</strong> uses a mesh to define the shape of the collider.  <strong>Mesh Collider</strong> can produce more accurate representations of the collision shape of the object, but it is much more expensive to compute collision detection on complex mesh colliders than using primitive colliders (The Box, Sphere, and Capsule colliders are considered primitive colliders).  Don&#8217;t use a mesh collider when a primitive collider will work just as well.</p>
<div id="attachment_4067" class="wp-caption alignnone" style="width: 753px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Mesh-Collider-2.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Mesh-Collider-2.png" alt="Unity - Mesh Collider" title="Unity - Mesh Collider" width="743" height="542" class="size-full wp-image-4067" /></a><p class="wp-caption-text">Unity &#8211; Mesh Collider</p></div>
<p>The Mesh Collider has the following properties:</p>
<ul>
<li><strong>Is Trigger</strong>: If <strong>true</strong>, this collider will be considered a <strong>Trigger Collider</strong> and will no longer be influenced by physics but it will fire <strong>Trigger</strong> events on other <strong>Rigidbody</strong> colliders.</li>
<li><strong>Material</strong>: The <strong>Physics Material</strong> that determines the friction and bounce of this object. The <strong>Physics Material</strong> is irrelevant if this is a <strong>Trigger Collider</strong>.
<li><strong>Convex</strong>: If the <strong>Convex</strong> property is <strong>true</strong>, a simplified version of the mesh collider will be generated.  Convex mesh colliders will collide with other <strong>Mesh Colliders</strong>.</li>
<li><strong>Smooth Sphere Collision</strong>: Collision mesh normals are smoothed across the collision faces.  This should be enabled on gradually slopped surfaces such as terrains and roads.</li>
<li><strong>Mesh</strong>: The Mesh asset that is used to generate the collision mesh for this Mesh Collider.</li>
</ul>
<p><strong>Primitive Rigidbody Colliders</strong> will perform collision detection on <strong>Static Mesh Colliders</strong> but <strong>Rigidbody Mesh Colliders</strong> will not collide with other <strong>Mesh Colliders</strong> unless one of them is set to <strong>Convex</strong>.</p>
<span id="Compound_Colliders"><h2>Compound Colliders</h2></span>
<p>Sometimes it is better to combine several primitive colliders to represent an object rather than use a complex mesh collider. Or maybe you want to combine several objects together so they behave as a single object.</p>
<p>To do this, we simply create a parent-child hierarchy of colliders.</p>
<div id="attachment_4068" class="wp-caption alignnone" style="width: 875px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Complex-Colliders.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Complex-Colliders.png" alt="Unity - Complex Colliders" title="Unity - Complex Colliders" width="865" height="600" class="size-full wp-image-4068" /></a><p class="wp-caption-text">Unity &#8211; Complex Colliders</p></div>
<p>The image above shows a <strong>Cylinder</strong> with a <strong>Sphere</strong> at each end of it.  The <strong>Sphere</strong> GameObjects are parented to the <strong>Cylinder</strong> GameObject.  As a result, the combination of all three GameObjects will behave as a single object.  If you need the GameObject to be physics controlled, then add a <strong>Rigidbody</strong> component to the top-level object only. Do not add <strong>Rigidbody</strong> components to the child GameObjects (if you do, they will behave as separate objects and break off the compound shape).</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-BoxCollider.html" title="Box Collider" target="_blank">Source</a>]</p>
<span id="Rigidbodies"><h1>Rigidbodies</h1></span>
<p>The <strong>Rigidbody</strong> component is required for objects to act under the influence of Physics.  You can apply forces and torques to the <strong>Rigidbody</strong> component from scripts or you can directly manipulate the linear and angular velocity of the <strong>Rigidbody</strong> if you want more control over it&#8217;s behavior.</p>
<p>A <strong>Rigidbody</strong> component requires a <strong>Collider</strong> component to be present on the GameObject for correct Physics simulation.</p>
<p>A <strong>Rigidbody</strong> can either be Physics controlled or <strong>Kinematic</strong> controlled.</p>
<span id="Physics_Rigidbody"><h2>Physics Rigidbody</h2></span>
<p>A <strong>Physics Rigidbody</strong> is fully controlled by the Physics engine. You can apply forces and torques to manipulate the linear and angular velocities but you cannot move the Rigidbody directly by using the GameObject&#8217;s Transform component (well, actually you can update the position and orientation of a Physics Rigidbody but it isn&#8217;t recommended).</p>
<p>To create a <strong>Physics Rigidbody</strong>, simply add the <strong>Rigidbody</strong> component to the GameObject you want to be influenced by physics and make sure the <strong>Is Kinematic</strong> property is not checked.</p>
<div id="attachment_4084" class="wp-caption alignnone" style="width: 713px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Rigidbody-Properties.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Rigidbody-Properties.png" alt="Unity - Physics Properties" title="Unity - Physics Rigidbody" width="703" height="484" class="size-full wp-image-4084" /></a><p class="wp-caption-text">Unity &#8211; Physics Rigidbody</p></div>
<span id="Kinematic_Rigidbody"><h2>Kinematic Rigidbody</h2></span>
<p>A <strong>Kinematic Rigidbody</strong> will not act under the influence of the physics engine.  You cannot apply forces or torques to to a <strong>Kinematic Rigidbody</strong> (well, actually you can apply forces and torques to a <strong>Kinematic Rigidbody</strong> but they just wont do anything). You also cannot rely on the Rigidbody&#8217;s linear and angular velocity properties being valid.</p>
<p>The only way you can move a <strong>Kinematic Rigidbody</strong> around the scene is by directly updating the GameObject&#8217;s Transform component.</p>
<div id="attachment_4086" class="wp-caption alignnone" style="width: 713px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Kinematic-Rigidbody.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Kinematic-Rigidbody.png" alt="Unity - Kinematic Rigidbody" title="Unity - Kinematic Rigidbody" width="703" height="484" class="size-full wp-image-4086" /></a><p class="wp-caption-text">Unity &#8211; Kinematic Rigidbody</p></div>
<span id="Properties_of_a_Rigidbody"><h2>Properties of a Rigidbody</h2></span>
<p>The <strong>Rigidbody</strong> component has the following properties:</p>
<ul>
<li><strong>Mass</strong>: The mass of the <strong>Rigidbody</strong>.  The mass of a <strong>Rigidbody</strong> should be based on the relative size and density of the object it is attached to.  For example, a large feather will have a much lower mass than relatively small rock or stone.  The mass has a direct influence on how much force is required to move the <strong>Rigidbody</strong>.  A very large mass will require more force to move it than a similar sized object with less mass.  If you remember the formula <img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?F=ma" style="float:top;" border="0px" /> from your basic physics lessons, then you will know that in order to get am object that weighs 10 kg to a speed of 5 meters per second (<strong>m/s</strong>) in just one second, you must apply a force of 50 newtons (<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?N=kg\frac{m}{s^2}" style="float:top;" border="0px" />) assuming we neglect all other external forces such as friction, drag, and gravity.   An object that has a mass of 5 kg only requires 25 newtons to accelerate it to a speed of 5 meters per second in one second.</li>
<li><strong>Drag</strong>: The <strong>Drag</strong> parameters controls how fast the object the object&#8217;s linear velocity is reduced due to air resistance.  With a <strong>Drag</strong> value of 0, the object will not be affected by air resistance (this simulates how Rigidbodies will behave in outer space). A very high drag can be used to make the object slow down very quickly if no external forces are applied to the rigidbody.  An object with a mass of 1 requires a <strong>Drag</strong> value of approximately 998 to resist the force of gravity.</li>
<li><strong>Angular Drag</strong>: The <strong>Angular Drag</strong> property is similar to the <strong>Linear Drag</strong> property in that it is used to slow the angular velocity of the <strong>Rigidbody</strong>.  If you want your <strong>Rigidbodies</strong> to stop spinning very quickly, set the <strong>Angular Drag</strong> property to a high value. A value of 0 will allow the Rigidbody to keep spinning indefinitely unless acted upon by an external force (such as friction).
</li>
<li><strong>Use Gravity</strong>: Should this <strong>Rigidbody</strong> be affected by gravity?</li>
<li><strong>Is Kinematic</strong>: This property should be set to true if you want to directly control the position and orientation of the <strong>Rigidbody</strong> using the <strong>GameObject&#8217;s</strong> <strong>Transform</strong> component. <strong>Kinematic Rigid Bodies</strong> will not be influenced by physics and will only collide with other non-kinematic <strong>Rigidbody Colliders</strong>.  <strong>Kinematic Rigidbodies</strong> will not collide with <strong>Static Colliders</strong> or other <strong>Kinematic Rigidbodies</strong>.</li>
<li><strong>Interpolate</strong>: If you find that your <strong>Rigidbody</strong> is not moving smoothly, you can adjust the interpolation method.
<ul>
<li><strong>None</strong>: The position and orientation of the <strong>Rigidbody</strong> is not smoothed between frames. This is the default value.</li>
<li><strong>Interpolate</strong>: The position and orientation of the <strong>Rigidbody</strong> is smoothed based on the position and orientation of the previous frame.</li>
<li><strong>Extrapolate</strong>: The position and orientation of the <strong>Rigidbody</strong> is smoothed based on the estimated position and orientation of the next frame.</li>
</ul>
</li>
<li><strong>Collision Detection</strong>: This property determines how this <strong>Rigidbody</strong> performs collision detection with other <strong>Rigidbodies</strong> in the scene.
<ul>
<li><strong>Discreet</strong>: This is the simplest form of collision detection. At each frame, the current position and orientation of the object is sampled and collision intersection tests are performed on nearby colliders. Using this method of collision detection, it is possible that small, fast moving objects will appear to pass directly through solid objects.</li>
<li><strong>Continuous</strong>: This <strong>Rigidbody</strong> will perform <strong>Continuous Collision Detection</strong> (<strong>CCD</strong>) against other <strong>Static Colliders</strong> and also on <strong>Rigidbody Colliders</strong> whose <strong>Collision Detection</strong> method is set to <strong>Continuous Dynamic</strong>.  On all other collider types, it will only perform <strong>Discreet</strong> collision detection.</li>
<li><strong>Continuous Dynamic</strong>: You should only set this value on fast moving objects. <strong>Rigidbodies</strong> whose <strong>Collision Detection</strong> method is set to <strong>Continuous Dynamic</strong> will perform <strong>CCD</strong> on other <strong>Rigidbodies</strong> that are either set to <strong>Continuous</strong> or <strong>Continuous Dynamic</strong>.  <strong>Continuous Dynamic Rigidbodies</strong> will also perform <strong>CCD</strong> on <strong>Static Colliders</strong>. For all other collider types, it will only perform <strong>Discreet</strong> collision detection.</li>
</ul>
</li>
<li><strong>Constraints</strong>: The position and orientation of the Rigidbody can be constrained so that it doesn&#8217;t move or rotate along specific axes.  These constraints will not effect <strong>Kinematic Rigidbodies</strong>.
<ul>
<li><strong>Freeze Position</strong>: Constrain the linear motion of the <strong>Rigidbody</strong> along one or more global axes. This is useful if you are making a 2D game and you don&#8217;t want objects to fly towards or away from the viewer. To prevent motion in the depth, you can simply constrain the motion in the Z-axis.</li>
<li><strong>Freeze Rotation</strong>: To prevent an object from rotation due to Torque forces, you can constrain the rotation of the <strong>Rigidbody</strong> along one or more global axes. This may be useful if you want to make a 2D game and you only want objects to rotate around the look-at direction. In this case, you would constrain both the X and Y axes and allow free rotation along the Z-axes.</li>
</ul>
</li>
</ul>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Rigidbody.html" title="Rigidbody" target="_blank">Source</a>]</p>
<span id="Rigidbody_Tutorial"><h2>Rigidbody Tutorial</h2></span>
<p>In some cases, you may want to represent your main character by another shape other than an upright capsule.  Maybe your main character is a cube, or a sphere? The <strong>Character Controller</strong> component (described in the next section) may not be suitable for you in this case. But how can we get a <strong>Rigidbody Collider</strong> to act like a Character Controller?</p>
<span id="Create_a_New_Scene"><h3>Create a New Scene</h3></span>
<p>Open Unity and either open an existing project or create a new one.</p>
<p>Create a new Scene if you don&#8217;t already have one.</p>
<div id="attachment_4132" class="wp-caption alignnone" style="width: 1148px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Unity-Rigidbody-Tutorial-1.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Unity-Rigidbody-Tutorial-1.png" alt="Unity - Rigidbody Tutorial (1)" title="Unity - Rigidbody Tutorial (1)" width="1138" height="746" class="size-full wp-image-4132" /></a><p class="wp-caption-text">Unity &#8211; Rigidbody Tutorial (1)</p></div>
<span id="Create_a_Plane"><h3>Create a Plane</h3></span>
<p>Add a <strong>Plane GameObject</strong> and set it&#8217;s properties to:</p>
<ul>
<li><strong>Plane</strong>
<ul>
<li><strong>Position</strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: 0</li>
<li><strong>Z</strong>: 0</li>
</ul>
</li>
<li><strong>Rotation</strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: 0</li>
<li><strong>Z</strong>: 0</li>
</ul>
</li>
<li><strong>Scale</strong>
<ul>
<li><strong>X</strong>: 10</li>
<li><strong>Y</strong>: 1</li>
<li><strong>Z</strong>: 10</li>
</ul>
</li>
</ul>
</li>
</ul>
<span id="Create_a_Rigidbody_Collider"><h3>Create a Rigidbody Collider</h3></span>
<p>Create a <strong>Cube</strong> GameObject and add a <strong>Rigidbody</strong> component to it.  Place it just above the plane so that it doesn&#8217;t fall through.  Rename the cube to &#8220;<strong>Rigidbody Collider</strong>&#8221;</p>
<div id="attachment_4135" class="wp-caption alignnone" style="width: 1148px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Unity-Rigidbody-Tutorial-2.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Unity-Rigidbody-Tutorial-2.png" alt="Unity - Rigidbody Tutorial (2)" title="Unity - Rigidbody Tutorial (2)" width="1138" height="746" class="size-full wp-image-4135" /></a><p class="wp-caption-text">Unity &#8211; Rigidbody Tutorial (2)</p></div>
<p>Create a red Diffuse material and add it to the newly created cube (to learn about materials, refer to my previous article titled <a href="http://3dgep.com/?p=3856" title="Rendering and Special Effects in Unity 3.5" target="_blank">Render and Special Effects in Unity 3.5</a>).</p>
<div id="attachment_4136" class="wp-caption alignnone" style="width: 1148px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Unity-Rigidbody-Tutorial-3.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Unity-Rigidbody-Tutorial-3.png" alt="Unity - Rigidbody Tutorial (3)" title="Unity - Rigidbody Tutorial (3)" width="1138" height="746" class="size-full wp-image-4136" /></a><p class="wp-caption-text">Unity &#8211; Rigidbody Tutorial (3)</p></div>
<span id="Create_a_Static_Collider"><h3>Create a Static Collider</h3></span>
<p>Create another cube without a Rigidbody.  Make this one blue.  Rename the GameObject to &#8220;<strong>Static Collider</strong>&#8220;.</p>
<div id="attachment_4137" class="wp-caption alignnone" style="width: 1148px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Unity-Rigidbody-Tutorial-4.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Unity-Rigidbody-Tutorial-4.png" alt="Unity - Rigidbody Tutorial (4)" title="Unity - Rigidbody Tutorial (4)" width="1138" height="746" class="size-full wp-image-4137" /></a><p class="wp-caption-text">Unity &#8211; Rigidbody Tutorial (4)</p></div>
<span id="Create_a_Trigger_Collider"><h3>Create a Trigger Collider</h3></span>
<p>Create another cube without a Rigidbody and set the <strong>Is Trigger</strong> property on the <strong>Box Collider</strong> to <strong>true</strong>.  Make it green and rename the GameObject to &#8220;<strong>Trigger Collider</strong>&#8220;.</p>
<div id="attachment_4138" class="wp-caption alignnone" style="width: 1148px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Unity-Rigidbody-Tutorial-5.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Unity-Rigidbody-Tutorial-5.png" alt="Unity - Rigidbody Tutorial (5)" title="Unity - Rigidbody Tutorial (5)" width="1138" height="746" class="size-full wp-image-4138" /></a><p class="wp-caption-text">Unity &#8211; Rigidbody Tutorial (5)</p></div>
<span id="Trigger_Script"><h3>Trigger Script</h3></span>
<p>Add the following JavaScript (let&#8217;s call the script &#8220;TriggerAnimation.js&#8221;) to the <strong>Trigger Collider</strong> GameObject:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="TriggerAnimation.js">
#pragma strict

@script RequireComponent(AudioSource)
@script RequireComponent(Animation)

var animationClip : AnimationClip;

var enterAudioClip : AudioClip;
var exitAudioClip : AudioClip;

function Awake()
{
	// Add the animation clip and make it default.
	animation.AddClip( animationClip, animationClip.name );
	animation.clip = animationClip;
}

function OnTriggerEnter( other : Collider )
{
	animation[animationClip.name].speed = 1.0;
	animation[animationClip.name].time = 0.0f;
	animation.Play();
	
	audio.clip = enterAudioClip;
	audio.Play();
}

function OnTriggerExit( other : Collider )
{
	animation[animationClip.name].speed = -1.0;
	animation[animationClip.name].time = animation[animationClip.name].length;
	animation.Play();
	
	audio.clip = exitAudioClip;
	audio.Play();
}
</pre>
</div>
<p>This script simply plays an Animation Clip and Audio Clip when another <strong>Rigidbody Collider</strong> enters and exits the area defined by the <strong>Trigger Collider</strong>.</p>
<p>Create a simple <strong>Animation Clip</strong> using the <strong>Animation</strong> view and drag-and-drop the animation clip from the <strong>Project</strong> view on to the the <strong>Animation Clip</strong> property for <strong>Trigger Animation</strong> script component in the <strong>Inspector</strong> view.</p>
<p>Get two <strong>Audio Clip</strong> assets and drag-and-drop the audio clips from the <strong>Project</strong> view onto the <strong>Enter Audio Clip</strong> and <strong>Exit Audio Clip</strong> properties for the <strong>Trigger Animation</strong> script component in the <strong>Inspector</strong> view. </p>
<span id="Create_a_Controllable_Rigidbody"><h3>Create a Controllable Rigidbody</h3></span>
<p>Add a fourth cube GameObject to the scene. Rename this GameObject to &#8220;<strong>Rigidbody Controller</strong>&#8220;.</p>
<div id="attachment_4143" class="wp-caption alignnone" style="width: 1148px"><a href="http://3dgep.com/wp-content/uploads/2012/10/Unity-Rigidbody-Tutorial-6.png"><img src="http://3dgep.com/wp-content/uploads/2012/10/Unity-Rigidbody-Tutorial-6.png" alt="Unity - Rigidbody Tutorial (6)" title="Unity - Rigidbody Tutorial (6)" width="1138" height="746" class="size-full wp-image-4143" /></a><p class="wp-caption-text">Unity &#8211; Rigidbody Tutorial (6)</p></div>
<p>Add the following JavaScript (let&#8217;s call it &#8220;RigidbodyController.js&#8221;) to the <strong>Rigidbody Controller</strong> GameObject.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="RigidbodyController.js">
#pragma strict

@script RequireComponent(Rigidbody)

private var isGrounded = false;

enum MotionMethod
{
	VELOCITY_BASED_MOTION,
	MOVE_BASED_MOTION,
}

var motionMethod = MotionMethod.VELOCITY_BASED_MOTION;

// Multiply the velocity when using the velocity based motion.
var velocityMultiplier = 200.0f;

// Multiply the move distance when using move based motion.
var moveMultipler = 5.0f;

// Multiply the force to make the cube jump.
var jumpMultipler = 500.0f;

function FixedUpdate() 
{
	// Calculate the velocity/move direction based on the user input.
	var moveDirection = Vector3( Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical") ) * Time.deltaTime;
	moveDirection = Camera.main.transform.TransformDirection( moveDirection );
	
	if ( rigidbody != null &amp;&amp; !rigidbody.isKinematic )
	{
		switch ( motionMethod )
		{
			case MotionMethod.VELOCITY_BASED_MOTION:
				// Speed up the rigidbocy in the x-z plane. The velocy in the y-axis is maintained so that gravity still works.
				rigidbody.velocity = Vector3( moveDirection.x * velocityMultiplier, rigidbody.velocity.y, moveDirection.z * velocityMultiplier);
				break;

			case MotionMethod.MOVE_BASED_MOTION:

				rigidbody.MovePosition( rigidbody.position + ( moveDirection * moveMultipler ) );
				// Zero the velocity in the X,Z plane.
				// We could do this by "Freezing" the X, Z position of the rigid body in the inspector, but then it would
				// pass-through other rigid bodies without doing collision.
				rigidbody.velocity = Vector3( 0, rigidbody.velocity.y, 0 );
				break;
		}
	
		if ( Input.GetButtonDown("Jump") &amp;&amp; isGrounded )
		{
			rigidbody.AddForce( Vector3.up * jumpMultipler );
		}
	}
	else
	{
		// Static Colliders and Kinematic Rigidbody Colliders manipulate the transform directly.
		transform.position += moveDirection;
	}
}

function  OnCollisionStay(collisionInfo : Collision)
{	
	// To be more accurate, you may want to check if the collision normal 
	// is pointing in the opposite direction as gravity.  Then it is more reasonable to 
	// assume that it is colliding with the ground.
	isGrounded = true;
}

function OnCollisionExit( collisionInfo : Collision )
{
	isGrounded = false;
}
</pre>
</div>
<p>The <strong>RequireComponent</strong> script attribute ensures that the <strong>GameObject</strong> that this script is being attached to will have a <strong>Rigidbody</strong> component attached to it.</p>
<p>We also declare a private variable called <strong>isGrounded</strong> which is used to check if the character is currently standing on the ground.</p>
<p>The <strong>Enumeration</strong> called <strong>MotionMethod</strong> is used to switch between velocity-based motion (where the velocity of the <strong>Rigidbody</strong> is directly affected in order to make the <strong>Rigidbody</strong> move, and move-based motion where the rigidbody is moved using the <strong>Rigidbody.MovePosition</strong> method to move the rigidbody.  By default, we will use velocity-based motion.</p>
<p>On lines 16, 19, and 22 a few public variables are declared that will be used to multiply the base veclocity, move speed, and jump height to achieve the desired movement.</p>
<p>Since we are performing motion operations on Physics bodies, we should perform these operations in the <strong>FixedUpdate</strong> method (as opposed to the Update method).  The reason for this was discussed in the article titled &#8220;<a href="http://3dgep.com/?p=3474" title="Scripting in Unity" target="_blank">Scripting in Unity</a>&#8220;.</p>
<p>In the <strong>FixedUpdate</strong> method, we first determine the relative direction to move based on the input axes.  The <strong>moveDirection</strong> vector is transformed by the transformation matrix of the main camera.  This makes the move direction always relative to whatever direction the main camera is facing (so left is always left and right is always right depending on the direction the camera is facing).</p>
<p>On line 30, we first check to see if the rigidbody component is set to <strong>Kinematic</strong>. If it isn&#8217;t then we will use the rigidbody&#8217;s velocity property to move the rigidbody through the scene.</p>
<p>If the motion method property is set to velocity-based motion (the first case) then we will create a vector that will be used to manipulate the velocity of the rigidbody directly.  Notice that we don&#8217;t change the Y-axis of the velocity vector. We do this because we don&#8217;t want to cancel the effect of gravity on the rigidbody. </p>
<p>If the motion method property is set to move-based motion (the second case) then we use the rigidbody&#8217;s <strong>MovePosition</strong> method to move the rigidbody in the scene.  If we use this method to move the rigidbody, then we must also zero the veloctiy (line 45). If we don&#8217;t do this, the rigidbody will maintain any velocity that may have been introduced by a collision. Notice that I don&#8217;t zero the velocity in the Y-axis because I don&#8217;t want to remove the effect of gravity.</p>
<p>On line 49, we apply a &#8220;Jump&#8221; force only if the rigidbody is grounded (we don&#8217;t want to allow jumping in mid-air).  The jump is applied as an upward force on the rigidbody multiplied by the <strong>jumpMultiplier</strong>.</p>
<p>The <strong>else</strong> statement on line 54 will be executed if the rigidbody is set to a <strong>Kinematic Rigidbody</strong>. In this case, the rigidbody will be moved by manipulating it&#8217;s <strong>Transform</strong> component directly.</p>
<p>The <strong>OnCollisionStay</strong> and <strong>OnCollisionExit</strong> functions are used to determine if the rigidbody is on the ground or not.</p>
<p>If you play the game now, you may notice the Rigidbody Controller cube will move, but it rolls&#8230;  How can we fix this?</p>
<p>Hint: Frictionless Physic Material.</p>
<span id="Character_Controller"><h1>Character Controller</h1></span>
<p>The <strong>Character Controller</strong> component is commonly used on upright biped characters.  Using a <strong>Character Controller</strong> does not require a <strong>Rigidbody</strong> to be present on the character to get the character to move.  Although collision detection will work correctly on <strong>Character Controllers</strong>, collision resolution will not work automatically; that is, when a Character Controller hits a <strong>Rigidbody Collider</strong>, it will not automatically apply forces to the <strong>Rigidbody Collider</strong> in order to get it to move.  If you want a (non-static) <strong>Rigidbody Collider</strong> to react to the <strong>Character Controller</strong> colliding with it, you must script this yourself.</p>
<div id="attachment_4096" class="wp-caption alignnone" style="width: 758px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Character-Controller-2.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Character-Controller-2.png" alt="Unity - Character Controller" title="Unity - Character Controller" width="748" height="563" class="size-full wp-image-4096" /></a><p class="wp-caption-text">Unity &#8211; Character Controller</p></div>
<p>The image above shows the green capsule around the Constructor character.  The green capsule shows the radius and height of the <strong>Capsule Collider</strong> created by the <strong>Character Controller</strong>.  It is currently not possible to change the collision shape of the <strong>Character Controller</strong> to something other than a <strong>Capsule</strong>.</p>
<p>The Character Controller has the following properties:</p>
<ul>
<li><strong>Slope Limit</strong>: The maximum slope angle (measured in degrees) the character controller can walk up before he will be pushed back.  This is useful for preventing your character from climbing steep slopes on a terrain for example.</li>
<li><strong>Step Offset</strong>: The maximum height the character controller will step over.  If an obstacle is higher than <strong>Step Offset</strong> above the current height of the character controller (measured from the ground), the Character Controller will be blocked by that obstacle.  Otherwise, he will step onto the obstacle.  Of course, if you want your character to visually look like he is stepping onto the obstacle, you must create an animation for that and play it at the right time.</li>
<li><strong>Skin Width</strong>: This value allows the Collider to interpenetrate with other Colliders.  If your character motion is jittery or your character is getting stuck in some cases, chances are your <strong>Skin Width</strong> is too low.  A good rule of thumb is the <strong>Skin Width</strong> should be about 10% of the <strong>Radius</strong> property.</li>
<li><strong>Min Move Distance</strong>: If the character is moved less distance than this value, the character will not move at all.  Generally, this value should be left at 0.</li>
<li><strong>Center</strong>: The center point of the <strong>Capsule Collider</strong> relative to the GameObject&#8217;s position.</li>
<li><strong>Radius</strong>: The width of the <strong>Capsule Collider</strong> along the Y-axis.  If your character seems to be able to walk partially through walls, you may want to increase the <strong>Radius</strong> value. If you character can&#8217;t get close enough to objects, you may want to decrease the <strong>Radius</strong> value.
<li><strong>Height</strong>: The height of the <strong>Capsule Collider</strong>.  If the character seems to be floating above the ground, you will want to decrease the <strong>Height</strong> value. If the character&#8217;s feet are sinking into the ground, then you will want to increase the <strong>Height</strong> value.</li>
</ul>
<span id="Character_Controller_Tutorial"><h2>Character Controller Tutorial</h2></span>
<p>What do we do if we want our <strong>Character Controller</strong> to apply forces to other <strong>Rigidbody Colliders</strong>?  The only way we can accomplish this is to apply a force to the other <strong>Rigidbody Collider</strong> in script.</p>
<span id="Create_a_New_Scene_1"><h3>Create a New Scene</h3></span>
<p>Open Unity with an existing project, or create a new project and create a new Scene.</p>
<div id="attachment_4099" class="wp-caption alignnone" style="width: 1164px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Character-Controller-Tutorial-1.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Character-Controller-Tutorial-1.png" alt="Unity - Character Controller Tutorial (1)" title="Unity - Character Controller Tutorial (1)" width="1154" height="750" class="size-full wp-image-4099" /></a><p class="wp-caption-text">Unity &#8211; Character Controller Tutorial (1)</p></div>
<p>Add a <strong>Plane GameObject</strong> and set it&#8217;s properties to:</p>
<ul>
<li><strong>Plane</strong>
<ul>
<li><strong>Position</strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: 0</li>
<li><strong>Z</strong>: 0</li>
</ul>
</li>
<li><strong>Rotation</strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: 0</li>
<li><strong>Z</strong>: 0</li>
</ul>
</li>
<li><strong>Scale</strong>
<ul>
<li><strong>X</strong>: 10</li>
<li><strong>Y</strong>: 1</li>
<li><strong>Z</strong>: 10</li>
</ul>
</li>
</ul>
</li>
</ul>
<div id="attachment_4101" class="wp-caption alignnone" style="width: 1164px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Character-Controller-Tutorial-2.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Character-Controller-Tutorial-2.png" alt="Unity - Character Controller Tutorial (2)" title="Unity - Character Controller Tutorial (2)" width="1154" height="750" class="size-full wp-image-4101" /></a><p class="wp-caption-text">Unity &#8211; Character Controller Tutorial (2)</p></div>
<p>Add a <strong>Cube</strong> and a <strong>Sphere</strong> GameObject to your scene.  Make sure they are placed just above the <strong>Plane</strong> so that they are not intersecting with the <strong>Plane</strong>.</p>
<div id="attachment_4102" class="wp-caption alignnone" style="width: 1164px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Character-Controller-Tutorial-3.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Character-Controller-Tutorial-3.png" alt="Unity - Character Controller Tutorial (3)" title="Unity - Character Controller Tutorial (3)" width="1154" height="750" class="size-full wp-image-4102" /></a><p class="wp-caption-text">Unity &#8211; Character Controller Tutorial (3)</p></div>
<p>Add a <strong>Rigidbody Component</strong> to both the <strong>Cube</strong> and the <strong>Sphere</strong> GameObject.  This will allow them to be influenced by Physics.</p>
<p>Duplicate (Ctrl+D) the <strong>Cube</strong> and the <strong>Sphere</strong> objects a few times in your scene and place the duplicates so that they are neither intersecting each other nor the <strong>Plane</strong>.</p>
<div id="attachment_4105" class="wp-caption alignnone" style="width: 1164px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Character-Controller-Tutorial-4.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Character-Controller-Tutorial-4.png" alt="Unity - Character Controller Tutorial (4)" title="Unity - Character Controller Tutorial (4)" width="1154" height="750" class="size-full wp-image-4105" /></a><p class="wp-caption-text">Unity &#8211; Character Controller Tutorial (4)</p></div>
<p>Add a light to your scene to illuminate the objects.</p>
<div id="attachment_4106" class="wp-caption alignnone" style="width: 1164px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Character-Controller-Tutorial-5.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Character-Controller-Tutorial-5.png" alt="Unity - Character Controller Tutorial (5)" title="Unity - Character Controller Tutorial (5)" width="1154" height="750" class="size-full wp-image-4106" /></a><p class="wp-caption-text">Unity &#8211; Character Controller Tutorial (5)</p></div>
<p>Optionally, you can also add various <strong>Physic Materials</strong> to the GameObjects to see how different values for the Physic Material effect the way the <strong>Rigidbody Colliders</strong> react to being pushed.  If you havn&#8217;t done so already, you can import the <strong>Physic Material</strong> standard package that comes with Unity by selecting <strong>Assets -> Import Package -> Physic Material</strong> from the main menu.   You can also create a frictionless material by following the steps outlined in the section about <a href="#Physics_Material">Physics Materials</a>.</p>
<span id="Add_a_Character_Controller"><h3>Add a Character Controller</h3></span>
<p>If you haven&#8217;t done so already, import the <strong>Character Controller</strong> standard package into your project (select <strong>Assets -> Import Package -> Character Controller</strong> from the main menu).</p>
<p>The Character Controller prefab provides prefabs for a standard first-person controller and a third-person controller.</p>
<p>Drag-and-drop the &#8220;<strong>3rd Person Controller</strong>&#8221; prefab from the &#8220;Standard Assets\Character Controllers&#8221; folder in your project view into the scene.  Make sure the character is placed above and not intersecting with the <strong>Plane</strong>.</p>
<div id="attachment_4109" class="wp-caption alignnone" style="width: 1164px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Character-Controller-Tutorial-6.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Character-Controller-Tutorial-6.png" alt="Unity - Character Controller Tutorial (6)" title="Unity - Character Controller Tutorial (6)" width="1154" height="750" class="size-full wp-image-4109" /></a><p class="wp-caption-text">Unity &#8211; Character Controller Tutorial (6)</p></div>
<p>In the <strong>Third Person Controller</strong> script component attached to the <strong>3rd Person Controller</strong> prefab you just created, make sure you set the <strong>Idle Animation</strong> property to the <strong>idle</strong> Animation Clip, the <strong>Walk Animation</strong> property to the <strong>walk</strong> animation clip, the <strong>Run Animation</strong> property to the <strong>run</strong> animation clip, and the <strong>Jump Pose Animation</strong> property to the <strong>jump_pose</strong> animation clip.</p>
<p>If you play this now, you will notice that the Constructor character will collide with the Rigidbody Colliders in the scene, but will not push any of them out of the way.</p>
<span id="Character_Controller_Push_Script"><h3>Character Controller Push Script</h3></span>
<p>Fortunately, we can create a script that will push the <strong>Rigidbody Colliders</strong> by applying a force to the <strong>Rigidbody</strong> when the Character Controller collides with it.</p>
<p>Create a new JavaScript script asset in your project.  You can call it whatever you want, but I called mine &#8220;<strong>CharacterControllerPushRigidbody</strong>&#8220;.</p>
<p>Open the newly created script in Mono and add the following code:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="CharacterControllerPushRigidbody.js">
#pragma strict

var forceMode : ForceMode = ForceMode.VelocityChange;
var pushPower = 2.0f;

function OnControllerColliderHit (hit : ControllerColliderHit) 
{
	// Get the hit rigidbody (if there is one).
    var body : Rigidbody = hit.rigidbody;

    // no rigidbody
    if (body == null || body.isKinematic)
        return;
        
    // We dont want to push objects below us
    if (hit.moveDirection.y < -0.3) 
        return;
    
    // Calculate push direction from move direction, 
    // we only push objects to the sides never up and down
    var pushDir : Vector3 = Vector3 (hit.moveDirection.x, 0, hit.moveDirection.z);

    // Apply the push
	body.AddForceAtPosition( pushDir * pushPower, hit.point, forceMode );
}
</pre>
</div>
<p>The first thing we see in this script (after the "#pragma strict" statement) is a variable called <strong>forceMode</strong> of type <strong>ForceMode</strong>. This variable determines how the force is applied to the <strong>Rigidbody</strong> that we collided with.  The <strong>ForceMode</strong> enumeration has the following values:</p>
<ul>
<li><strong>Force</strong>: Adds a force to the <strong>Rigidbody</strong> taking the <strong>Rigidbody</strong>'s mass into consideration.  Using this method, larger forces will be needed in order to accelerate <strong>Rigidbodies</strong> with greater mass.</li>
<li><strong>Acceleration</strong>: Adds a continuous acceleration to the <strong>Rigidbody</strong>, ignoring it's mass.  Using this mode, the object will immediately accelerate regardless of it's mass.</li>
<li><strong>Impulse</strong>: Adds an instatnous force impulse to the <strong>Rigidbody</strong> taking it's mass into consideration.</li>
<li><strong>VelocityChange</strong>: Instantly changes the velocity of the Rigidbody regardless of it's mass.</li>
</ul>
<p>On line 4, we declare a variable called <strong>pushPower</strong>. This value determines the amount of force, acceleration, impulse, or velocity (depending on the value of the <strong>forceMode</strong> variable) that will be applied to the <strong>Rigidbody</strong> we collided with.</p>
<p>On line 6, we declare a function called <strong>OnControllerColliderHit</strong>. This method is valid on GameObjects with a <strong>Character Controller</strong> component attached to them.  It is invoked when the <strong>Character Controller</strong> collides with another <strong>Collider</strong> (<strong>Rididbody Collider</strong> or <strong>Static Collider</strong>)  while performing a <strong>Move</strong>.  This method takes a single argument called <strong>hit</strong> of type <strong>ControllerColliderHit</strong> that is used to determine which other <strong>Collider</strong> was hit and where it was hit.</p>
<p>On line 9, we extract the <strong>Rigidbody</strong> component that was hit (if there is one).</p>
<p>If the <strong>Collider</strong> we hit is a <strong>Static Collider</strong> (that is, it does not have a <strong>Rigidbody</strong>) or it is a <strong>Kinematic Rigidbody Collider</strong> (in which case, it is not physics controlled), then we don't want to do anything.</p>
<p>For this script, we will also ignore collisions that occured while the <strong>Character Controller</strong> is falling (it's move direction in the Y-axis is less than 0).</p>
<p>On line 21, we create a direction vector which represents the direction the Character Controller was moving (in the XZ-plane) when the collision occured.</p>
<p>And finally on line 24, we apply a force to the Rigidbody at a paticular point in global space.  This is done by calling the <strong>AddForceAtPosition</strong> method on the <strong>Rigidbody</strong>.</p>
<p>The <strong>Rigidbody.AddForceAtPosition</strong> function takes the following arguments.</p>
<ul>
<li><strong>force : Vector3</strong>: The direction and magnitude of the force to apply to the <strong>Rigidbody</strong>.</li>
<li><strong>position : Vector3</strong>: The position in world space to apply the force.  If this position is not the same as the current position of the <strong>Rigidbody</strong> then an angular force as well as a linear force will be applied to the <strong>Rigidbody</strong>. This could cause the <strong>Rigidbody</strong> to start spinning.</li>
<li><strong>mode : ForceMode</strong>: The type of force that will be applied to the <strong>Rigidbody</strong> (see <strong>ForceMode</strong> described above).</li>
</ul>
<p>Now attach this script to your <strong>3rd Person Controller</strong> GameObject and run the game again.  Your character should be able to push the <strong>Rigidbody Colliders</strong> out of the way if he tries to walk through them.</p>
<p>Don't forget to save your scene.</p>
<span id="Try_This..."><h3>Try This...</h3></span>
<p>Assign different <strong>Physic Materials</strong> to the <strong>Rigidbodies</strong> to see how it changes the way the <strong>Character Controller</strong> interacts with them.</p>
<p>Change the value of the <strong>Push Power</strong> property to change the amount of force that is applied to the <strong>Rigidbody</strong>.</p>
<p>Change the <strong>Force Mode</strong> property. Which mode works the best?</p>
<span id="Joints"><h1>Joints</h1></span>
<p>Unity provides several types of <strong>Joints</strong> that you can use in your scene.  A <strong>Joint</strong> is a constraint that is defined between two <strong>Rigidbodies</strong>.  For example, the <strong>Hinge Joint</strong> can be used to create a door that can swing open along a particular axis.</p>
<p>A <strong>Spring Joint</strong> can be used to create an invisible spring that tries to keep two rigid bodies together.</p>
<p>A <strong>Fixed Joint</strong> can be used to keep two <strong>Rigidbody</strong> objects together at a constant distance and orientation. This is useful if you need to "parent" a <strong>Rigidbody</strong> to another <strong>Rigidbody</strong> and possibly them to break-apart if the force or torque between them exceeds a certain threshold.</p>
<p>The <strong>Configurable Joint</strong> allows you to create complex joint configuration that can either mimic the Spring and Hinge joint types, but also allow you to create other types of joints as well (such as pivot, ball-and-socket, saddle, and gliding joints).</p>
<span id="Hinge_Joint"><h2>Hinge Joint</h2></span>
<p>A <strong>Hinge Joint</strong> component can be used to constrain one <strong>Rigidbody</strong> to another along a particular axis.</p>
<p>The GameObject that will be used to create a <strong>Hinge Joint</strong> must have a <strong>Rigidbody</strong> component.  If you don't want the Rigidbody to be influenced by the forces applied by the joint, then make the <strong>Rigidbody</strong> <strong>Kinematic</strong>.</p>
<p>When referring to the Rigidbody components that participate in the joint constraint, the <strong>Primary</strong> body will refer to the Rigidbody that defines the joint and the <strong>Connected</strong> body will refer to the Rigidbody that is connected to the joint.</p>
<div id="attachment_4122" class="wp-caption alignnone" style="width: 373px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Hinge-Joint.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Hinge-Joint.png" alt="Unity - Hinge Joint" title="Unity - Hinge Joint" width="363" height="604" class="size-full wp-image-4122" /></a><p class="wp-caption-text">Unity - Hinge Joint</p></div>
<p>The <strong>Hinge Joint</strong> has the following properties:</p>
<ul>
<li><strong>Connected Body</strong>: The other <strong>Rigidbody</strong> that this hinge joint is dependent on.  This parameter is optional. If it is not specified, then it will be connected to a fixed point in space.  This is simlar to attaching the joint to a <strong>Kinematic Rigidbody</strong>.</li>
<li><strong>Anchor</strong>: The <strong>Anchor</strong> point defines the position of the joint relative to the primary body.  This will be the point at which the primary and connected bodies rotate.</li>
<li><strong>Axis</strong>: The axis of rotation for the joint relative to the primary body. For a door hinge, this will alsmost always be (0,1,0) (if the primary body isn't rotated).</li>
<li><strong>Use Spring</strong>: If <strong>Use Spring</strong> is checked, then the spring properties will be used to apply a spring force on the hinge joint that will try to keep the primary and connected Rigidbodies at a relative angle from eachother.
<ul>
<li><strong>Spring</strong>: The spring force constant to apply to the joint to try to get to the target angle.  Greater values will create a very strong spring while lower values will create a weak spring.</li>
<li><strong>Damper</strong>: The damper is used to slow the spring recoil.  If you don't want the spring to overshoot when it recoils, set the <strong>Damper</strong> value high. If you want the spring to overshoot and swing back and forth before it comes to rest, set the damper value to 0.</li>
<li><strong>Target Position</strong>: This property is actually used determine the relative angle (measured in degrees) where the rest is considered "at rest".  This angle can be animated at runtime through scripting to simulate automatic opening doors.</li>
</ul>
</li>
<li><strong>Use Motor</strong>: If this value is checked, then a motor force will be applied to the hinge joint.  The motor joint can be used to simulate propellors, turnstiles, or revolving doors.
<ul>
<li><strong>Target Velocity</strong>: The motor will try to maintain this velocity (measured in degrees per second) to keep the hinge rotating around it's <strong>Axis</strong>.</li>
<li><strong>Force</strong>: The amount of force to apply to the joint in order to maintain the desired velocity.  With a force of 0, the motor will not start working until it is influenced by an outside force and it will stop very easily if something gets in it's way.  With a large force, it will start spinning immediatly and it will push other Rigibodies out of the way if they are hit by the Rigidbody attached to the hinge.</li>
<li><strong>Free Spin</strong>: If enabled, the motor will not be used to slow the joint's rotation velocity (if for example, it starts spinning faster than the <strong>Target Velocity</strong> because an external force hit the door very hard) but it will only be used to accelerate the door to the <strong>Target Velocity</strong> if it was spinning slower.</li>
</ul>
</li>
<li><strong>Use Limits</strong>: If this is checked, then angular limits will be imposed on the hinge joint.
<ul>
<li><strong>Min</strong>: The minimum angle (measured in degrees) that this hinge can swing.</li>
<li><strong>Max</strong>: The maximum angle (measured in degrees) that this hinge can swing.</li>
<li><strong>Min Bounce</strong>: How much the hinge will bounce when it reaches the minumum limit angle. A bounce value of 0 will cause the hinge not to bounce while a bounce value of 1 will cause the hinge to bounce with no loss of energy.</li>
<li><strong>Max Bounce</strong>: How much the hinge will bounce when it reaches the maximum limit angle. A bounce value of 0 will cause the hinge not to bounce while a bounce value of 1 will cause the hinge to bounce with no loss of energy.</li>
</ul>
</li>
<li><strong>Break Force</strong>: If the amount of linear force imposed on the hinge joint is greater than this value, the hinge will break and the participating Rigidbodies will no longer be constratined.</li>
<li><strong>Break Torque</strong>: If the amount of angular force imposed on the hinge joint is greater than this value, the hinge will break and the participating Rigidbodies will no longer be constratined.</li>
</ul>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-HingeJoint.html" title="Hinge Joint" target="_blank">Source</a>]</p>
<span id="Spring_Joint"><h2>Spring Joint</h2></span>
<p>TODO</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-SpringJoint.html" title="Spring Joint" target="_blank">Source</a>]</p>
<span id="Fixed_Joint"><h2>Fixed Joint</h2></span>
<p>TODO</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-FixedJoint.html" title="Fixed Joint" target="_blank">Source</a>]</p>
<span id="Character_Joint"><h2>Character Joint</h2></span>
<p>TODO</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-CharacterJoint.html" title="Character Joint" target="_blank">Source</a>]</p>
<span id="Conclusion"><h1>Conclusion</h1></span>
<span id="References"><h1>References</h1></span>
<p>The <a href="http://docs.unity3d.com/Documentation/Components/index.html" title="Unity Component Reference Manual" target="_blank">Unity Component Reference Manual</a> was used to gather the information required to write this article.</p>
<p>The Unity Component Reference Manual can be accessed here:</p>
<p><a href="http://docs.unity3d.com/Documentation/Components/index.html" title="Unity Component Reference Manual" target="_blank">http://docs.unity3d.com/Documentation/Components/index.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://3dgep.com/?feed=rss2&#038;p=4027</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Rendering and Special Effects in Unity 3.5</title>
		<link>http://3dgep.com/?p=3856</link>
		<comments>http://3dgep.com/?p=3856#comments</comments>
		<pubDate>Mon, 24 Sep 2012 14:29:32 +0000</pubDate>
		<dc:creator>Jeremiah van Oosten</dc:creator>
				<category><![CDATA[Unity]]></category>
		<category><![CDATA[Bumpmapping]]></category>
		<category><![CDATA[Camera]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[diffuse]]></category>
		<category><![CDATA[Effects]]></category>
		<category><![CDATA[Emissive]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[Lightmapping]]></category>
		<category><![CDATA[Lights]]></category>
		<category><![CDATA[materials]]></category>
		<category><![CDATA[Normalmapping]]></category>
		<category><![CDATA[Parallax]]></category>
		<category><![CDATA[specular]]></category>

		<guid isPermaLink="false">http://3dgep.com/?p=3856</guid>
		<description><![CDATA[In this article, I will introduce the reader to the different rendering components in Unity. I will introduce the Camera component as well as the different lighting components that are available.  I will also talk about materials in Unity and introduce you to a few of the shaders that are available.  And finally, I will also introduce light-mapping in Unity.  
 <a href="http://3dgep.com/?p=3856">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="attachment_4024" class="wp-caption alignleft" style="width: 160px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Lightmapping-2012-09-24-15-03-42-66.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Lightmapping-2012-09-24-15-03-42-66-150x150.png" alt="Lightmapping" title="Lightmapping" width="150" height="150" class="size-thumbnail wp-image-4024" /></a><p class="wp-caption-text">Lightmapping</p></div>
<p>In this article, I will introduce the reader to the different rendering components in Unity. I will introduce the Camera component as well as the different lighting components that are available.  I will also talk about materials in Unity and introduce you to a few of the shaders that are available.  And finally, I will also introduce light-mapping in Unity.  </p>
<p>If you haven&#8217;t used Unity before, you can refer to my previous article titled &#8220;<a href="http://3dgep.com/?p=3246" title="Introduction to Unity 3.5">Introduction to Unity</a>&#8221; available here: <a href="http://3dgep.com/?p=3246" title="Introduction to Unity 3.5">http://3dgep.com/?p=3246</a>.</p>
<p><span id="more-3856"></span></p>
<div style="clear: both;"><div class='toc wptoc'>
<h2>Table of Contents</h2>
<ol class='toc-odd level-1'>
	<li>
		<a href="#Introduction">Introduction</a>
	</li>
	<li>
		<a href="#Rendering_Components">Rendering Components</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Camera">Camera</a>
				<ol class='toc-odd level-3'>
					<li>
						<a href="#About_Cameras">About Cameras</a>
						<ol class='toc-even level-4'>
							<li>
								<a href="#Position_and_Orientation">Position and Orientation</a>
							</li>
							<li>
								<a href="#Projection">Projection</a>
							</li>
						</ol>
					<li>
						<a href="#Camera_Component">Camera Component</a>
					</li>
				</ol>
			<li>
				<a href="#Skybox">Skybox</a>
			</li>
			<li>
				<a href="#Lights">Lights</a>
				<ol class='toc-odd level-3'>
					<li>
						<a href="#Directional_Lights">Directional Lights</a>
					</li>
					<li>
						<a href="#Point_Lights">Point Lights</a>
					</li>
					<li>
						<a href="#Spot_Lights">Spot Lights</a>
					</li>
					<li>
						<a href="#Light_Properties">Light Properties</a>
					</li>
				</ol>
</ol>
			<li>
				<a href="#Materials_and_Shaders">Materials and Shaders</a>
				<ol class='toc-even level-2'>
					<li>
						<a href="#Normal_Shaders">Normal Shaders</a>
						<ol class='toc-odd level-3'>
							<li>
								<a href="#Vertex_Lit">Vertex Lit</a>
							</li>
							<li>
								<a href="#Diffuse">Diffuse</a>
							</li>
							<li>
								<a href="#Specular">Specular</a>
							</li>
							<li>
								<a href="#Bumped_Diffuse">Bumped Diffuse</a>
							</li>
							<li>
								<a href="#Bumped_Specular">Bumped Specular</a>
							</li>
							<li>
								<a href="#Parallax_Diffuse">Parallax Diffuse</a>
							</li>
							<li>
								<a href="#Parallax_Specular">Parallax Specular</a>
							</li>
							<li>
								<a href="#Decal">Decal</a>
							</li>
							<li>
								<a href="#Diffuse_Detail">Diffuse Detail</a>
							</li>
						</ol>
					<li>
						<a href="#Transparent_Shaders">Transparent Shaders</a>
					</li>
					<li>
						<a href="#Transparent_Cutout_Shaders">Transparent Cutout Shaders</a>
					</li>
					<li>
						<a href="#Self-Illuminated_Shaders">Self-Illuminated Shaders</a>
					</li>
					<li>
						<a href="#Reflective_Shaders">Reflective Shaders</a>
					</li>
				</ol>
			<li>
				<a href="#Light_Mapping">Light Mapping</a>
				<ol class='toc-even level-2'>
					<li>
						<a href="#Create_a_New_Scene">Create a New Scene</a>
					</li>
					<li>
						<a href="#Create_a_Box">Create a Box</a>
					</li>
					<li>
						<a href="#Add_Some_Color">Add Some Color</a>
					</li>
					<li>
						<a href="#Create_a_Light">Create a Light</a>
					</li>
					<li>
						<a href="#Create_the_Lightmap">Create the Lightmap</a>
						<ol class='toc-odd level-3'>
							<li>
								<a href="#Single_vs_Dual_Lightmaps">Single vs Dual Lightmaps</a>
							</li>
							<li>
								<a href="#Direct_vs_Indirect_Lighting">Direct vs Indirect Lighting</a>
							</li>
						</ol>
					<li>
						<a href="#Bake_Settings">Bake Settings</a>
					</li>
					<li>
						<a href="#Make_Objects_Static">Make Objects Static</a>
					</li>
					<li>
						<a href="#Ligtmapping_Lights">Ligtmapping Lights</a>
					</li>
					<li>
						<a href="#Emissive_Materials_Pro_Only">Emissive Materials (Pro Only)</a>
					</li>
					<li>
						<a href="#Emissive_Materials_on_Dynamic_Objects">Emissive Materials on Dynamic Objects</a>
					</li>
				</ol>
			<li>
				<a href="#Conclusion">Conclusion</a>
			</li>
			<li>
				<a href="#Resources">Resources</a>
			</li>
</ol>
</div>
<div class='wptoc-end'>&nbsp;</div></div>
<span id="Introduction"><h1>Introduction</h1></span>
<p>Lighting and special effects are an integral part of every polished game.  Lighting is very import when setting the general mood or atmosphere of your game.  Proper lighting can mean the difference between a game that looks like it has been made by a group of programmers, or a highly polished game made by professionals.  The general mood of your game is set by the use of lighting in your levels.  To convey a mood of &#8220;fear&#8221; is achieved through sparse use of lighting in strategic locations. However, you can achieve the opposite mood by using bright lights that bring out the vivid colors of your game.</p>
<p>Lighting can be achieved using a few dynamic light sources, or through a process known as lightmapping where the lighting information is rendered into a texture that is placed on the static objects in your scene.  But the best application of lighting is a combination of both dynamic light sources and baked lightmapping.</p>
<p>Special effects are used to add that &#8220;wow&#8221; factor to your game. When used correctly, they can add an extra boost to your gameplay that will keep the players coming back for more.  In this article, I will introduce the Shuriken particle editor that was added to Unity in version 3.5.  I will talk about the various module that are used to make an individual particle system and how you can combine particle systems to make complex particle effects.</p>
<p>I will also introduce a technique called lightmapping.  Unity includes the <strong>Beast</strong> lightmapper and doesn&#8217;t require a pro license to use it.</p>
<span id="Rendering_Components"><h1>Rendering Components</h1></span>
<p>The <strong>Render Components</strong> are the group of components that effect in-game rendering such as cameras and lights.</p>
<span id="Camera"><h2>Camera</h2></span>
<p>The <strong>Camera</strong> component is used to capture a view of the world and display it to the player.  Without at least one <strong>Camera</strong> component attached to a GameObject in the scene, you will simply see a gray screen.  When you create a new scene, Unity will automatically place a single GameObject called &#8220;<strong>Main Camera</strong>&#8221; in your new scene by default.</p>
<p>You can have as many cameras in your scene as you want, but generally you will only have one main camera that is used to display your game.</p>
<div id="attachment_3862" class="wp-caption alignnone" style="width: 970px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Camera-Component.gif"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Camera-Component.gif" alt="Unity - Camera Component" title="Unity - Camera Component" width="960" height="656" class="size-full wp-image-3862" /></a><p class="wp-caption-text">Unity &#8211; Camera Component</p></div>
<span id="About_Cameras"><h3>About Cameras</h3></span>
<p>The <strong>Camera</strong> determines what you see and how it appears on screen.  The camera has several properties that are common to all camera types regardless if it is used by Unity or not.  It is important to understand these properties to properly configure your camera&#8217;s view.  These properties include position and orientation, projection, near and far clipping planes, field of view (for perspective projection), size (width and height for orthographic projection), and in some cases viewport size.</p>
<span id="Position_and_Orientation"><h4>Position and Orientation</h4></span>
<p>In Unity, the <strong>Camera</strong> component is attached to a <strong>GameObject</strong> that is placed in your scene. The <strong>GameObject&#8217;s</strong> position and orientation in the world will determine what the <strong>Camera</strong> is looking at.  The Camera will always look in the direction of the <strong>GameObject&#8217;s</strong> positive <strong>Z</strong> axis.</p>
<div id="attachment_3875" class="wp-caption alignnone" style="width: 703px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Camera-View2.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Camera-View2.png" alt="Unity - Camera View" title="Unity - Camera View" width="693" height="565" class="size-full wp-image-3875" /></a><p class="wp-caption-text">Unity &#8211; Camera View &#8211; Perspective</p></div>
<p>As can be seen in the image, the camera is pointing in the positive Z axis (represented by the blue arrow in the image).</p>
<span id="Projection"><h4>Projection</h4></span>
<p>The <strong>Projection</strong> determines how objects are mapped from a 3D space (usually View Space) into a clipped camera space (called Clip Space).  There are two common types of projections that can be applied to the camera: <strong>Perspective Projection</strong> or <strong>Orthographic Projection</strong>.</p>
<span id="Perspective_Projection"><h5>Perspective Projection</h5></span>
<p>A <strong>Perspective Projection</strong> is the most common type of projection you will use in your game.  Using this type of projection, objects that are close to the camera will appear larger than objects that are placed farther away from the camera.  This is also how the human eye works.</p>
<p>Using a <strong>Perspective Projection</strong> an additional property becomes available called the <strong>Field of View</strong>.  This value measures the vertical viewing angle. Making the <strong>Field of View</strong> angle smaller (closer to 0), objects will appear zoomed-in and making the <strong>Field of View</strong> larger (angle closer to 180) will cause objects to appear zoomed-out.</p>
<p>Using this type of projection the <strong>View Frustum</strong> resembles a <strong>Pyramid</strong> with it&#8217;s top cut-off (see the image above).</p>
<span id="Orthographic_Projection"><h5>Orthographic Projection</h5></span>
<p>An <strong>Orthographic Projection</strong> is more commonly used for 2D side-scrolling or platforming games. The Orthographic projection is also useful when displaying GUI elements on screen (although Unity handles this for your when you use GUITexture and GUIText and when using the GUI API to create menus). With an <strong>Orthographic Projection</strong>, objects will appear the same size regardless of how far they are from the camera.</p>
<p>Using the <strong>Orthographic Projection</strong> you will have an additional property called <strong>Size</strong> that determines the width and height (but not the depth) of the view frustum.  Making the <strong>Size</strong> smaller will cause objects to appear zoomed-in and making the <strong>Size</strong> larger will cause objects to appear zoomed-out.</p>
<p>The shape of the <strong>View Frustum</strong> resembles an elongated box (see image below).</p>
<div id="attachment_3877" class="wp-caption alignnone" style="width: 703px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Camera-View-Orthographic.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Camera-View-Orthographic.png" alt="Unity - Camera View - Orthographic" title="Unity - Camera View - Orthographic" width="693" height="567" class="size-full wp-image-3877" /></a><p class="wp-caption-text">Unity &#8211; Camera View &#8211; Orthographic</p></div>
<span id="Camera_Component"><h3>Camera Component</h3></span>
<p>The <strong>Camera</strong> component has the following properties:</p>
<div id="attachment_3862" class="wp-caption alignnone" style="width: 970px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Camera-Component.gif"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Camera-Component.gif" alt="Unity - Camera Component" title="Unity - Camera Component" width="960" height="656" class="size-full wp-image-3862" /></a><p class="wp-caption-text">Unity &#8211; Camera Component</p></div>
<ul>
<li><strong>Clear Flags</strong>: Determines how the screen is cleared before the scene is rendered.  The following options are available:
<ul>
<li><strong>Skybox</strong>: This is the default clear flag. If the <strong>GameObject</strong> the <strong>Camera</strong> component is attached to also has a <strong>Skybox</strong> component, the <strong>Skybox</strong> material will be used to clear the screen before rendering.  If no <strong>Skybox</strong> is configured, the <strong>Background</strong> color property is used to clear the screen.</li>
<li><strong>Solid Color</strong>: Use the <strong>Background</strong> color to clear the screen.</li>
<li><strong>Depth Only</strong>: Do not clear the color buffer, only clear the depth buffer.  This is useful for some post-processing effects where only the depth values are taken into consideration.</li>
<li><strong>Don&#8217;t Clear</strong>: Neither the color buffer nor the depth buffer are cleared.</li>
</ul>
</li>
<li><strong>Background</strong>: Specifies a background color to use when either <strong>Solid Color</strong> is specified for the <strong>Clear Flags</strong> or when <strong>Skybox</strong> is specified for the <strong>Clear Flags</strong> but no <strong>Skybox</strong> has been configured.</li>
<li><strong>Culling Mask</strong>: The <strong>Culling Mask</strong> property allows you to specify which <strong>Layers</strong> should be rendered with this <strong>Camera</strong> component.  By default, all layers are rendered.</li>
<li><strong>Projection</strong>: Specifies the type of camera view.  Valid values are <strong>Perspective</strong> and <strong>Orthographic</strong>.
<ul>
<li><strong>Perspective</strong>: This is the default view type. With a <strong>Perspective</strong> projection objects closer to the <strong>Camera</strong> will appear larger than objects farther away.  This is the default view and the one most commonly used to render 3D games.</li>
<li><strong>Orthographic</strong>: With an <strong>Orthographic</strong> projection, objects that are farther away from the <strong>Camera</strong> will not appear smaller than objects closer to the <strong>Camera</strong>. In other words, objects in your game will not demonstrate perspective.  This view type is useful for 2D games, isometric games, and top-down views of your game world (for example, to generate a mini-map display).
</li>
</ul>
</li>
<li><strong>Field of View</strong>: This option is only available when the <strong>Projection</strong> property is set to <strong>Perspective</strong>. This option controls the zoom level of your <strong>Camera</strong>.  This is similar to putting a zoom lens on your own <strong>Camera</strong> or looking through a pair of binoculars.  With a smaller field of view, objects will appear zoomed-in but with a large field of view, things will appear very far away.  The default value is 60 degrees but values in the range of 45 degrees to 90 degrees will generally still look okay.  Smaller or larger field of view may appear distorted.</li>
<li><strong>Size</strong>: This option is only available when the <strong>Projection</strong> property is set to <strong>Orthographic</strong>.  This property determines the size of the box that is formed by the orthographic view.  Making the orthographic size smaller will make the objects in your scene appear zoomed-in and making the size larger will make the objects in your scene appear zoomed-out.</li>
<li><strong>Clipping Planes</strong>: The clipping planes determine the range of your camera&#8217;s view.  Objects outside of the range of the clipping planes will be clipped.  It&#8217;s generally a good idea to keep the <strong>Near</strong> and <strong>Far</strong> clipping planes close together.  Setting the clipping planes too far apart will result in a rendering artifact known as <a href="http://en.wikipedia.org/wiki/Z-fighting" title="Z-Fighting" target="_blank">Z-Fighting</a>.
<ul>
<li><strong>Near</strong>: The <strong>Near</strong> clipping plane determines how close an object can be to the <strong>Camera</strong> before it will be clipped from view.  It is generally a good idea to keep this value in the range <strong>0.1</strong> to <strong>0.5</strong>.</li>
<li><strong>Far</strong>: The <strong>Far</strong> clipping plane determines how far an object can be from the <strong>Camera</strong> before it will be clipped from view.  This value should only be as large as absolutely necessary and not larger.  For indoor environments, the <strong>Far</strong> clipping plane can be set fairly close to the <strong>Near</strong> clipping plane since objects far away will be occluded by the walls of your level.  For outdoor scenes you may need to make <strong>Far</strong> clipping plane farther away but don&#8217;t make it larger than needed.</li>
</ul>
</li>
<li><strong>Normalized View Port Rect</strong>: The <strong>View Port Rect</strong> determines where this <strong>Camera</strong> will be rendered on the screen.  This parameter is useful for implementing split-screen gameplay.
<ul>
<li><strong>X</strong>: The normalized distance from the left side of the screen to display the view of the <strong>Camera</strong>.</li>
<li><strong>Y</strong>: The normalized distance from the bottom of the screen to display the view of the <strong>Camera</strong>.</li>
<li><strong>W</strong>: The normalized width of the view of the <strong>Camera</strong>.</li>
<li><strong>H</strong>: The normalized height of the view of the <strong>Camera</strong>.</li>
</ul>
</li>
<li><strong>Depth</strong>: This property determines the order in which this <strong>Camera</strong> will be rendered.  Valid values for the <strong>Depth</strong> of the <strong>Camera</strong> are <strong>-100</strong> to <strong>100</strong>.  <strong>Camera</strong> components with a lower <strong>Depth</strong> value will be rendered before <strong>Camera</strong> components with a higher <strong>Depth</strong> value.  The default value is <strong>0</strong>.
</li>
<li><strong>Rendering Path</strong>: This property determines the rendering method used for this <strong>Camera</strong>.
<ul>
<li><strong>Use Player Settings</strong>: The <strong>Camera</strong> will use whatever settings are configured in the <a href="http://docs.unity3d.com/Documentation/Components/class-PlayerSettings.html" title="Player Settings" target="_blank">Player Settings</a> dialog.</li>
<li><strong>Vertex Lit</strong>: Lighting is computed per-vertex instead of per-pixel. This rendering method is faster than forward rendering but produces lower quality renders.</li>
<li><strong>Forward</strong>: This is the standard rendering method used. It produces high quality results but is performance bound by the number of lights used in your scene.</li>
<li><strong>Deferred Lighting (Pro Only)</strong>: Deferred lighting means that lighting information will be computed after all other information (such as depth, screen-space normals, and specular contribution) has been rendered into several screen-space buffers (called the G-Buffer).  Deferred lighting allows for many dynamic lights to be computed efficiently.  Deferred lighting requires graphics hardware with support for Shader Model 3.0 (SM3.0) which is available on most desktop GPUs but currently not available on most mobile platforms.</li>
</ul>
</li>
<li><strong>Target Texture (Pro Only)</strong>: This allows you to specify a texture (actually a Render Target) where the view of the <strong>Camera</strong> will be rendered into.  This texture can then be applied as a standard texture to other objects in your scene.  This is useful for implementing things like a security camera in your scene that is displayed on a monitor somewhere else in the scene. It can also be used to create a &#8220;Picture-in-Picture&#8221; effect for your main GUI.  If set to <strong>None</strong> (the default value) then the <strong>Camera</strong> will render to the screen.</li>
<li><strong>HDR (Pro Only)</strong>: Enable High Dynamic Range rendering for this <strong>Camera</strong>.  By default, the red, green, and blue channels have a value in the range 0 to 1.0 (with 256 shades per channel). With HDR enabled, colors are stored as 32-bit floating-point values that can exceed 1.0.  This means that overly bright colors will be handled correctly and post-processing effects (like HDR bloom) can be applied correctly.  Before being rendered on-screen, the HDR colors will be shifted back in the 0 to 1.0 range using a technique called HDR tonemapping.  For more information about HDR rendering, please refer to the online documentation here: <a href="http://docs.unity3d.com/Documentation/Manual/HDR.html" title="HDR (High Dynamic Range)" target="_blank">http://docs.unity3d.com/Documentation/Manual/HDR.html</a></li>
</ul>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Camera.html" title="The Camera Component" target="_blank">Source</a>]</p>
<span id="Skybox"><h2>Skybox</h2></span>
<p>The <strong>Skybox</strong> component is used to draw an environment that appears infinitely far away from the camera.  You can imagine it as an infinitely large box that is centered at the position of the <strong>Camera</strong>.  The <strong>Skybox</strong> component has a single property called <strong>Custom Skybox</strong> which allows you to assign a skybox material.</p>
<div id="attachment_3882" class="wp-caption alignnone" style="width: 970px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Skybox-Component.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Skybox-Component.png" alt="Unity - Skybox Component" title="Unity - Skybox Component" width="960" height="656" class="size-full wp-image-3882" /></a><p class="wp-caption-text">Unity &#8211; Skybox Component</p></div>
<p>A Skybox material uses the <strong>RenderFX/Skybox</strong> Shader which uses 6 textures to render the sides of the skybox cube (front, back, left, right, top, and bottom).</p>
<div id="attachment_3883" class="wp-caption alignnone" style="width: 970px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Skybox-Material.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Skybox-Material.png" alt="Unity - Skybox Material" title="Unity - Skybox Material" width="960" height="656" class="size-full wp-image-3883" /></a><p class="wp-caption-text">Unity &#8211; Skybox Material</p></div>
<p>If you want to define a default <strong>Skybox</strong> that will be automatically applied to all cameras in your scene (whose <strong>Clear Flags</strong> parameter is set to <strong>Skybox</strong>) you can assign a <strong>Skybox</strong> material to the <strong>Skybox Material</strong> property in the <strong>Render Settings</strong> dialog (select <strong>Edit -> Render Settings</strong> from the main menu).</p>
<div id="attachment_3885" class="wp-caption alignnone" style="width: 970px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Render-Settings-Skybox-Material.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Render-Settings-Skybox-Material.png" alt="Unity - Render Settings - Skybox Material" title="Unity - Render Settings - Skybox Material" width="960" height="656" class="size-full wp-image-3885" /></a><p class="wp-caption-text">Unity &#8211; Render Settings &#8211; Skybox Material</p></div>
<p>If you specify the <strong>Skybox Material</strong> in the <strong>Render Settings</strong> dialog, that <strong>Skybox</strong> will also appear in the <strong>Scene</strong> view.</p>
<p>Unity comes with a few <strong>Skybox</strong> materials that you can use in your own games.  To import the <strong>Skyboxes</strong> package, select <strong>Assets -> Import Package -> Skyboxes</strong> from the main menu.</p>
<span id="Lights"><h2>Lights</h2></span>
<p>By default when you create a new scene, you will not have any lights in your scene. Without lights, all objects in the scene will have a dark-gray color.  This dark-gray color is the default color of the <strong>Ambient Light</strong> property defined in the <strong>Render Settings</strong> dialog (select <strong>Edit -> Render Settings</strong> from the main menu).</p>
<div id="attachment_3888" class="wp-caption alignnone" style="width: 866px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Ambient-Light-Only.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Ambient-Light-Only.png" alt="Unity - Ambient Light Only" title="Unity - Ambient Light Only" width="856" height="643" class="size-full wp-image-3888" /></a><p class="wp-caption-text">Unity &#8211; Ambient Light Only</p></div>
<p>Unity provides 3 light types (excluding the Area Light which is only available with the Pro license): </p>
<ul>
<li>Directional Lights</li>
<li>Point Lights</li>
<li>Spot Lights</li>
</ul>
<p>Each light type is implemented with the <strong>Light</strong> component but the light type is chosen from the <strong>Type</strong> property of the light.</p>
<span id="Directional_Lights"><h3>Directional Lights</h3></span>
<p><strong>Directional Lights</strong> are most common in outdoor scenes.  <strong>Directional Lights</strong> mimic the behavior of the Sun, that is, they will illuminate everything in the scene regardless of the position of the directional light relative to other objects in the scene.  If you place an object behind a directional light, the object will be lit according to the direction of the light but the position of the light will be ignored.  <strong>Directional Lights</strong> will always point in the direction of the <strong>GameObject</strong>&#8216;s Z axis.</p>
<div id="attachment_3893" class="wp-caption alignnone" style="width: 1024px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Directional-Light.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Directional-Light.png" alt="Unity - Directional Light" title="Unity - Directional Light" width="1014" height="644" class="size-full wp-image-3893" /></a><p class="wp-caption-text">Unity &#8211; Directional Light</p></div>
<p>As you can see from the image above, the directional light is placed above the sphere and pointing in the direction of the capsule, but all three shapes are lit as if the light was placed infinitely far away.</p>
<p><strong>Directional Lights</strong> are also the only light type that can be used to generate shadows in the default rendering mode (forward rendering). </p>
<div class="my-note">
Real-time dynamic shadows are only supported with a Unity Pro license but you can achieve static shadows using light mapping.
</div>
<span id="Point_Lights"><h3>Point Lights</h3></span>
<p>Point lights emit light evenly in all directions and unlike <strong>Directional Lights</strong>, the position of point lights is very important but their direction is irrelevant.</p>
<p>Point Lights are most commonly used as localized light sources such as light bulbs, illuminating explosions, or used to complement other particle effects like fire and flames.</p>
<div id="attachment_3896" class="wp-caption alignnone" style="width: 1024px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Point-Lights.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Point-Lights.png" alt="Unity - Point Lights" title="Unity - Point Lights" width="1014" height="644" class="size-full wp-image-3896" /></a><p class="wp-caption-text">Unity &#8211; Point Lights</p></div>
<p>As can be seen from the image, the <strong>Point Light</strong> has a maximum range indicated by the yellow sphere.  You can click and drag the handles on the yellow sphere to adjust the range of the light.</p>
<p>You will also notice that the intensity of the light decreases as the point being lit is further away from the light.  This effect is called <strong>Attenuation</strong> of the light.  The <strong>Attenuation</strong> of the light is dependent on both the <strong>Range</strong> and the <strong>Intensity</strong> of the light.</p>
<span id="Spot_Lights"><h3>Spot Lights</h3></span>
<p><strong>Spot Lights</strong> are a combination of <strong>Point Lights</strong> and <strong>Directional Lights</strong>.  The <strong>Spot Light</strong> is the only light type for which both the position and direction of the light are taken into consideration when computing the contribution of the light.  Just like <strong>Directional Lights</strong>, <strong>Spot Lights</strong> will always point in the direction of the <strong>GameObject</strong>&#8216;s positive Z axis.</p>
<p>Spot Lights are most commonly used as light sources for flashlights, headlights for a vehicle, or light emitting from a street lamp.</p>
<div id="attachment_3903" class="wp-caption alignnone" style="width: 1024px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Spotl-Light1.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Spotl-Light1.png" alt="Unity - Spotl Light" title="Unity - Spotl Light" width="1014" height="644" class="size-full wp-image-3903" /></a><p class="wp-caption-text">Unity &#8211; Spotl Light</p></div>
<p><strong>Spot Lights</strong> also exhibit <strong>Attenuation</strong> (as the point being lit is further away from the light, the intensity of the light decreases).  Again, the range and intensity of the light will contribute to the <strong>Attenuation</strong> of the light.</p>
<p>The size of the <strong>Spot Light&#8217;s</strong> cone angle is controlled by the <strong>Spot Angle</strong> property.  The intensity of the <strong>Spot Light</strong> is also effected by the difference in the angle to the spot being lit and the direction of the <strong>Spot Light</strong>.  As the angle between these increases, the intensity of the light decreases.  This effect is called intensity <strong>fall-off</strong>. This <strong>fall-off</strong> effect produces a more realistic lighting result but unfortunately, the intensity <strong>fall-off</strong> factor is not configurable in Unity.</p>
<span id="Light_Properties"><h3>Light Properties</h3></span>
<p>The <strong>Light</strong> component has the following properties:</p>
<ul>
<li><strong>Type</strong>: Determines the type of the Light component.
<ul>
<li><strong>Spot</strong>: A Spotlight which simulates a cone shaped light pointing in the local Z-axis.</li>
<li><strong>Directional</strong>: A Directional light which illuminates all objects in the scene from a single direction.  Position is irrelevant.</li>
<li><strong>Point</strong>: A Point light shines light in every direction equally. Only objects within <strong>Range</strong> distance are affected by the light.</li>
</ul>
</li>
<li><strong>Range</strong>: This property is only available if the <strong>Type</strong> is either <strong>Spot</strong> or <strong>Point</strong>.  This value determines the distance (in world units) at which the light will affect an object.  Objects beyond this distance from the light will not be illuminated by the light.</li>
<li><strong>Spot Angle</strong>: This property is only available if the <strong>Type</strong> is set to <strong>Spot</strong>.  This value determines the cone angle (measured in degrees) of the spotlight cone.</li>
<li><strong>Color</strong>: The primary color of the light.  This value determines both the diffuse and specular contributions of the light.</li>
<li><strong>Intensity</strong>: The brightness of the light.</li>
<li><strong>Cookie</strong>: The alpha channel of the <strong>Cookie</strong> texture is used to determine the brightness of the light.  If the <strong>Light</strong> is of <strong>Type</strong> <strong>Spot</strong> or <strong>Directional</strong>, then this must be a <strong>2D Texture</strong>.  If the <strong>Light</strong> is of <strong>Type</strong> <strong>Point</strong>, then this must be a <strong>Cubemap</strong>.</li>
<li><strong>Cookie Size</strong>: This property is only available if the <strong>Type</strong> is set to <strong>Directional</strong>. This property allows you to scale the cookie texture that is applied to the <strong>Directional</strong> light.</li>
<li><strong>Shadow Type (Pro only)</strong>: Shadows are only available with the Pro license. Using the <strong>Forward</strong> rendering path (see <a href="#Camera_Component" title="Camera Properties">Camera Properties</a>), only <strong>Directional</strong> lights produce shadows.  Using the <strong>Deferred</strong> rendering path, <strong>Point</strong> and <strong>Spot</strong> lights also produce shadows.
<ul>
<li><strong>No Shadows</strong>: This light does not produce shadows.</li>
<li><strong>Hard Shadows</strong>: The light produces hard shadows. This is the preferred method for generating shadows because it is cheaper to compute.</li>
<div id="attachment_3919" class="wp-caption alignnone" style="width: 574px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Hard-Shadows.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Hard-Shadows.png" alt="Unity - Hard Shadows" title="Unity - Hard Shadows" width="564" height="495" class="size-full wp-image-3919" /></a><p class="wp-caption-text">Unity &#8211; Hard Shadows</p></div>
<li><strong>Soft Shadows</strong>: This method produces shadows with blurred edges.  This method is slower than <strong>Hard Shadows</strong>, but it produces a better result.</li>
<div id="attachment_3920" class="wp-caption alignnone" style="width: 574px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Soft-Shadows.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Soft-Shadows.png" alt="Unity - Soft Shadows" title="Unity - Soft Shadows" width="564" height="495" class="size-full wp-image-3920" /></a><p class="wp-caption-text">Unity &#8211; Soft Shadows</p></div>
</ul>
</li>
<li><strong>Strength</strong>: The darkness of the shadow will be multiplied by this value to reduce the intensity of shadows produced by this light.</li>
<li><strong>Resolution</strong>: This property determines the size of the shadow map texture used by this light. <strong>Very High Resolution</strong> will produce better shadows at the expensive of speed and memory.</li>
<li><strong>Bias</strong>: If the light produces an effect called <strong>Shadow Acne</strong> then you can adjust the <strong>Bias</strong> parameter to resolve the artifacts.  However, setting the <strong>Bias</strong> parameter too high may cause <strong>Peter Panning</strong>.
<div id="attachment_3915" class="wp-caption alignnone" style="width: 574px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Shadow-Acne.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Shadow-Acne.png" alt="Unity - Shadow Acne" title="Unity - Shadow Acne" width="564" height="495" class="size-full wp-image-3915" /></a><p class="wp-caption-text">Unity &#8211; Shadow Acne</p></div>
<div id="attachment_3917" class="wp-caption alignnone" style="width: 569px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Peter-Panning.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Peter-Panning.png" alt="Unity - Peter Panning" title="Unity - Peter Panning" width="559" height="489" class="size-full wp-image-3917" /></a><p class="wp-caption-text">Unity &#8211; Peter Panning</p></div>
<p>In the image above, the cylinder appears to be &#8220;floating&#8221; above the plane when in fact, the cylinder is placed exactly on the plane.</p>
</li>
<li><strong>Softness</strong>: This parameter is only available if Shadow Type is set to <strong>Soft Shadows</strong>. This parameter is used to scale the size of the soft are of the shadow (the outer edge of the shadow where it begins to soften).  Valid values are in the range [1 .. 8].  With a value of 1, the shadow will appear to be a <strong>Hard Shadow</strong>.  With a value of 8, the shadow will appear soft around the &#8220;penumbra&#8221;.
<li><strong>Softness Fade</strong>: This parameter is only available when <strong>Shadow Type</strong> is set to <strong>Soft Shadows</strong>.  This value determines the intensity of the shadow penumbra (the soft edge of the shadow that is partially in shadow) based on the distance from the camera.</li>
<li><strong>Draw Halo</strong>: Draws a <strong>Halo</strong> effect at the position of the light. Although this property can be assigned to <strong>Directional</strong> lights, it usually doesn&#8217;t make sense to add this to a directional light because <strong>Directional</strong> lights don&#8217;t really have a position, only a direction.  This property should only be set on positional lights light <strong>Point</strong> and <strong>Spot</strong> lights.  Optionally, a Halo effect can also be achieved using a <strong>Halo</strong> component.</li>
<li><strong>Flare</strong>: Adds a <strong>Flare</strong> effect to the light.  The <strong>Flare</strong> effect mimics a <strong>Lens Flare</strong> effect that is seen on camera lenses in real reality.  This parameter accepts a <strong>Flare</strong> texture.  Optionally, this effect can be achieved using a <strong>Flare</strong> component.</li>
<li><strong>Render Mode</strong>: This property determines how and when the light is applied to objects.
<ul>
<li><strong>Auto</strong>: The quality of the light renderer is determined by the proximity and intensity of the light relative to the object being rendered.</li>
<li><strong>Important</strong>: This light will always be rendered using per-pixel lighting shaders.</li>
<li><strong>Not Important</strong>: This light will always be rendered using per-vertex lighting shaders.</li>
</ul>
</li>
<li><strong>Culling Mask</strong>: Include or exclude objects assigned to different layers from being affected by the light.</li>
<li><strong>Lightmapping</strong>: This property determines how this light contributes to the Ligthmapping process.
<ul>
<li><strong>Auto</strong>: Uses real-time dynamic lighting when the light is close to the camera and baked lighting information is used when the light is far away from the camera. This technique requires dual lightmaps to be baked for your scene.</li>
<li><strong>Realtime Only</strong>: Lighting information for this light will not be baked into the lightmap.  This is useful if your light&#8217;s properties (Color or Intensity for example) will change at run-time.</li>
<li><strong>Baked Only</strong>: This light is not simulated at run-time. It is only used as a light source for the light map.  This is useful for static lights that will not change at runtime. Do not use this setting on lights that should generate dynamic shadows at run-time.</li>
</ul>
</li>
</ul>
<span id="Materials_and_Shaders"><h1>Materials and Shaders</h1></span>
<p>A <strong>Shader</strong> is the source code that defines how a particular effect is rendered.  A <strong>Material</strong> uses a <strong>Shader</strong> and the <strong>Material</strong> exposes the properties defined in the <strong>Shader</strong> to the <strong>Inspector</strong>.  Also, you cannot apply a <strong>Shader</strong> directly to a <strong>GameObject</strong> in the scene, but instead you must apply a <strong>Material</strong> to the <strong>GameObject</strong>.</p>
<p>Unity provides a set of built-in shaders that you can use in your games.  The built-in shaders are split into groups called <strong>Shader Families</strong>.  Each <strong>Shader Family</strong> defines several variants of the base shader type for that family.</p>
<p>The different Shader Families you have available in Unity are:</p>
<ul>
<li><strong>Normal Shader Family</strong>: These are probably the most common shader type. It is used on opaque objects that do not need to appear transparent or light-emitting.</li>
<li><strong>Transparent Shader Family</strong>: These shaders are used on transparent objects that are either fully, or semi-transparent.</li>
<li><strong>Transparent Cutout Shader Family</strong>: These shaders are used on objects that have either opaque or fully transparent pixels. This is useful for solid objects that contain holes like a fence, or a chain link, or blades of grass.</li>
<li><strong>Self-Illuminated Shader Family</strong>: These shaders will simulate an object that emits light.  In this case, the object will appear lit even if there are no lights illuminating the object.  Objects with a Self-Illuminated shader applied to them will not illuminate other objects!</li>
<li><strong>Reflective Shader Family</strong>: These shaders allow you to apply a reflective cube map on the material.  The alpha channel of the base texture is used to determine the amount of reflectivity that is applied at each pixel.</li>
</ul>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/Built-inShaderGuide.html" title="Built-In Shader Guide" target="_blank">Source</a>]</p>
<span id="Normal_Shaders"><h2>Normal Shaders</h2></span>
<p>The <strong>Normal Shader Family</strong> define the most basic shaders used in Unity.  This shader type is used on opaque objects that do not have any transparency or emissive properties.</p>
<p>This shader family has several variants and each variant defines different properties that effect the way the shader is rendered.</p>
<span id="Vertex_Lit"><h3>Vertex Lit</h3></span>
<p>The <strong>Vertex Lit</strong> variant performs only per-vertex lighting and does not perform any per-fragment lighting or lighting effect that require per-fragment processing like light cookies, normal mapping, or shadows.</p>
<p>This is a fast shader and should be used whenever correct lighting results are not very important. It is recommended you use this shader type on small objects or objects that are placed far away from the camera.</p>
<div id="attachment_3999" class="wp-caption alignnone" style="width: 778px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Vertex-Lit.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Vertex-Lit.png" alt="Unity - Vertex Lit" title="Unity - Vertex Lit" width="768" height="450" class="size-full wp-image-3999" /></a><p class="wp-caption-text">Unity &#8211; Vertex Lit</p></div>
<p>The <strong>Vertex Lit</strong> shader has the following properties that are exposed in the <strong>Material</strong>:</p>
<ul>
<li><strong>Main Color</strong>: The <strong>Main Color</strong> property can be used to lighten or darken the <strong>Base</strong> texture.  If the <strong>Main Color</strong> is white, then the texture will appear as it is in the <strong>Base</strong> texture.  If it is black, then the texture will appear black.</li>
<li><strong>Sepc Color</strong>: This <strong>Spec Color</strong> is used to determine the color of the specular highlight.</li>
<li><strong>Emissive Color</strong>: The <strong>Emissive Color</strong> is added to the base texture and can be used to brighten the object even in the absence of light.</li>
<li><strong>Shininess</strong>: The <strong>Shininess</strong> property determines how shiny the surface of the object appears.  A low shininess value will result in a large specular highlight and a high shininess value will result in a small specular highlight.</li>
<div id="attachment_4001" class="wp-caption alignnone" style="width: 778px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Vertex-Lit-low-shininess.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Vertex-Lit-low-shininess.png" alt="Unity - Vertex Lit (low shininess)" title="Unity - Vertex Lit (low shininess)" width="768" height="450" class="size-full wp-image-4001" /></a><p class="wp-caption-text">Unity &#8211; Vertex Lit (low shininess)</p></div>
<div id="attachment_4002" class="wp-caption alignnone" style="width: 778px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Vertex-Lit-high-shininess.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Vertex-Lit-high-shininess.png" alt="Unity - Vertex Lit (high shininess)" title="Unity - Vertex Lit (high shininess)" width="768" height="450" class="size-full wp-image-4002" /></a><p class="wp-caption-text">Unity &#8211; Vertex Lit (high shininess)</p></div>
<li><strong>Base (RGB)</strong>: The <strong>Base</strong> texture that is used to apply the image to the object. Textures can be scaled on the object by adjusting the <strong>Tiling</strong> property and the texture can be offset by adjusting the <strong>Offset</strong> parameter.
<ul>
<li><strong>Tiling</strong>: This property determines how many times the texture is repeated across the surface of the object in each direction.</li>
<div id="attachment_4004" class="wp-caption alignnone" style="width: 778px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Vertex-Lit-2-x-Tiling.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Vertex-Lit-2-x-Tiling.png" alt="Unity - Vertex Lit (2 x Tiling)" title="Unity - Vertex Lit (2 x Tiling)" width="768" height="450" class="size-full wp-image-4004" /></a><p class="wp-caption-text">Unity &#8211; Vertex Lit (2 x Tiling)</p></div>
<div id="attachment_4005" class="wp-caption alignnone" style="width: 778px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Vertex-Lit-half-tiling.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Vertex-Lit-half-tiling.png" alt="Unity - Vertex Lit (half tiling)" title="Unity - Vertex Lit (half tiling)" width="768" height="450" class="size-full wp-image-4005" /></a><p class="wp-caption-text">Unity &#8211; Vertex Lit (half tiling)</p></div>
<li><strong>Offset</strong>: As the name suggests, the <strong>Offset</strong> parameter is used to shift the texture across the object.</li>
</ul>
</li>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/shader-NormalFamily.html" title="Normal Shader Family" target="_blank">Source</a>]</p>
<span id="Diffuse"><h3>Diffuse</h3></span>
<p>The <strong>Diffuse</strong> shader computes per-pixel lighting contribution using the <strong>Lambert reflectance</strong> lighting model.  This shader will not produce specular highlights.</p>
<div id="attachment_4007" class="wp-caption alignnone" style="width: 778px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Diffuse.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Diffuse.png" alt="Unity - Diffuse" title="Unity - Diffuse" width="768" height="450" class="size-full wp-image-4007" /></a><p class="wp-caption-text">Unity &#8211; Diffuse</p></div>
<span id="Specular"><h3>Specular</h3></span>
<p>The <strong>Specular</strong> shader adds an additional parameter to control the specular shininess.</p>
<div id="attachment_4009" class="wp-caption alignnone" style="width: 778px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Specular.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Specular.png" alt="Unity - Specular" title="Unity - Specular" width="768" height="450" class="size-full wp-image-4009" /></a><p class="wp-caption-text">Unity &#8211; Specular</p></div>
<span id="Bumped_Diffuse"><h3>Bumped Diffuse</h3></span>
<p>The <strong>Bumped Diffuse</strong> shader adds an additional texture parameter called the <strong>Normalmap</strong>.  The <strong>Normalmap</strong> texture is used to add additional detail to the surface of the object without adding additional vertices to the model.  This shader does not produce a specular highlight.</p>
<div id="attachment_4010" class="wp-caption alignnone" style="width: 778px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Bumped-Diffuse.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Bumped-Diffuse.png" alt="Unity - Bumped Diffuse" title="Unity - Bumped Diffuse" width="768" height="450" class="size-full wp-image-4010" /></a><p class="wp-caption-text">Unity &#8211; Bumped Diffuse</p></div>
<span id="Bumped_Specular"><h3>Bumped Specular</h3></span>
<p>The <strong>Bumped Specular</strong> shader adds a specular highlight property to the material.</p>
<div id="attachment_4012" class="wp-caption alignnone" style="width: 778px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Bumped-Specular.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Bumped-Specular.png" alt="Unity - Bumped Specular" title="Unity - Bumped Specular" width="768" height="450" class="size-full wp-image-4012" /></a><p class="wp-caption-text">Unity &#8211; Bumped Specular</p></div>
<span id="Parallax_Diffuse"><h3>Parallax Diffuse</h3></span>
<p>The <strong>Parallax Diffuse</strong> shader adds additional parameters for <strong>Height</strong> and <strong>Heightmap</strong>.  The <strong>Height</strong> property is a scalar property that is used to adjust the apparent height of the surface of the object and the <strong>Heightmap</strong> texture property uses the Alpha channel of the texture to determine high and low parts of the surface. The opaque parts of the alpha map will appear extruded while transparent parts of the alpha map will appear recessed.</p>
<p>This shader is generally applied to brick and mortar textures where you want the bricks to appear higher than the mortar grout.</p>
<div id="attachment_4014" class="wp-caption alignnone" style="width: 778px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Parallax-Diffuse.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Parallax-Diffuse.png" alt="Unity - Parallax Diffuse" title="Unity - Parallax Diffuse" width="768" height="450" class="size-full wp-image-4014" /></a><p class="wp-caption-text">Unity &#8211; Parallax Diffuse</p></div>
<span id="Parallax_Specular"><h3>Parallax Specular</h3></span>
<p>The <strong>Parallax Specular</strong> shader is similar to the Parallax Diffuse shader except it has an additional property for the <strong>Specular Color</strong> and the <strong>Shininess</strong> values.</p>
<div id="attachment_4016" class="wp-caption alignnone" style="width: 778px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Parallax-Specular.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Parallax-Specular.png" alt="Unity - Parallax Specular" title="Unity - Parallax Specular" width="768" height="450" class="size-full wp-image-4016" /></a><p class="wp-caption-text">Unity &#8211; Parallax Specular</p></div>
<span id="Decal"><h3>Decal</h3></span>
<p>The <strong>Decal</strong> shader is similar to the <strong>Diffuse</strong> shader with an additional texture that is placed on top of the original texture.  The <strong>Decal</strong> texture is not blended with the <strong>Base</strong> texture, it just replaces the pixel behind it.</p>
<div id="attachment_4018" class="wp-caption alignnone" style="width: 778px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Decal.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Decal.png" alt="Unity - Decal" title="Unity - Decal" width="768" height="450" class="size-full wp-image-4018" /></a><p class="wp-caption-text">Unity &#8211; Decal</p></div>
<span id="Diffuse_Detail"><h3>Diffuse Detail</h3></span>
<p>The <strong>Diffuse Detail</strong> shader exposes an addition texture parameter that is used to add detail to a texture when the camera is close to the surface.  The <strong>Detail</strong> texture will be faded-in as the camera gets close to the surface.  The purpose of this shader is to hide the filtering artifacts that become visible when you look closely at low-resolution textures.</p>
<div id="attachment_4021" class="wp-caption alignnone" style="width: 778px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Diffuse-Detail.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Diffuse-Detail.png" alt="Unity - Diffuse Detail" title="Unity - Diffuse Detail" width="768" height="450" class="size-full wp-image-4021" /></a><p class="wp-caption-text">Unity &#8211; Diffuse Detail</p></div>
<span id="Transparent_Shaders"><h2>Transparent Shaders</h2></span>
<p>TODO</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/shader-TransparentFamily.html" title="Transparent Shader Family" target="_blank">Source</a>]</p>
<span id="Transparent_Cutout_Shaders"><h2>Transparent Cutout Shaders</h2></span>
<p>TODO</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/shader-TransparentCutoutFamily.html" title="Transparent Cutout Shader Family" target="_blank">Source</a>]</p>
<span id="Self-Illuminated_Shaders"><h2>Self-Illuminated Shaders</h2></span>
<p>TODO</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/shader-SelfIllumFamily.html" title="Self-Illuminated Shader Family" target="_blank">Source</a>]</p>
<span id="Reflective_Shaders"><h2>Reflective Shaders</h2></span>
<p>TODO</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/shader-ReflectiveFamily.html" title="Reflective Shader Family" target="_blank">Source</a>]</p>
<span id="Light_Mapping"><h1>Light Mapping</h1></span>
<p>Lightmapping is the process of computing high-quality lighting information and storing this information in a texture.  This texture is &#8220;mapped&#8221; over the static objects in your scene which gives the impression of high-quality lighting at run-time.  The process of generating the light maps is called <strong>baking</strong> the lightmaps.</p>
<p>Unity comes with a built-in lightmapping program called <a href="http://gameware.autodesk.com/beast" title="Beast" target="_blank">Beast</a> that you can use in the free version of Unity to generate static lightmaps for your scenes.</p>
<p>To understand how lightmapping works in Unity, we will create a simple scene that uses lightmapping to generate direct and indirect lighting information for your scene.</p>
<span id="Create_a_New_Scene"><h2>Create a New Scene</h2></span>
<p>Start Unity and create a new empty project.  Let&#8217;s call this new project <strong>Lightmapping</strong>.  For this example, you do not need to import any of the standard packages.</p>
<div id="attachment_3926" class="wp-caption alignnone" style="width: 581px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-New-Project-Lightmapping.gif"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-New-Project-Lightmapping.gif" alt="Unity - New Project (Lightmapping)" title="Unity - New Project (Lightmapping)" width="571" height="365" class="size-full wp-image-3926" /></a><p class="wp-caption-text">Unity &#8211; New Project (Lightmapping)</p></div>
<p>Unity will automatically create a new empty scene for you.</p>
<div id="attachment_3927" class="wp-caption alignnone" style="width: 978px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-New-Scene-Lightmapping.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-New-Scene-Lightmapping.png" alt="Unity - New Scene (Lightmapping)" title="Unity - New Scene (Lightmapping)" width="968" height="642" class="size-full wp-image-3927" /></a><p class="wp-caption-text">Unity &#8211; New Scene (Lightmapping)</p></div>
<p>Save the scene and call it <strong>Lightmapping</strong>.</p>
<span id="Create_a_Box"><h2>Create a Box</h2></span>
<p>Create 5 planes in your scene with the following properties:</p>
<ul>
<li><strong>Back Plane</strong>
<ul>
<li><strong>Name</strong>: Back</li>
<li><strong>Position</strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: 0</li>
<li><strong>Z</strong>: 5</li>
</ul>
</li>
<li><strong>Rotation</strong>
<ul>
<li><strong>X</strong>: 270</li>
<li><strong>Y</strong>: 0</li>
<li><strong>Z</strong>: 0</li>
</ul>
</li>
</ul>
</li>
<li><strong>Bottom Plane </strong>
<ul>
<li><strong>Name</strong>: Bottom</li>
<li><strong>Position</strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: -5</li>
<li><strong>Z</strong>: 0</li>
</ul>
</li>
<li><strong>Rotation</strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: 0</li>
<li><strong>Z</strong>: 0</li>
</ul>
</li>
</ul>
</li>
<li><strong>Left Plane</strong>
<ul>
<li><strong>Name</strong>: Left</li>
<li><strong>Position</strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: -5</li>
<li><strong>Z</strong>: 0</li>
</ul>
</li>
<li><strong>Rotation </strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: 0</li>
<li><strong>Z</strong>: 270</li>
</ul>
</li>
</ul>
</li>
<li><strong>Right Plane</strong>
<ul>
<li><strong>Name</strong>: Right</li>
<li><strong>Position</strong>
<ul>
<li><strong>X</strong>: 5</li>
<li><strong>Y</strong>: 0</li>
<li><strong>Z</strong>: 0</li>
</ul>
</li>
<li><strong>Rotation </strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: 0</li>
<li><strong>Z</strong>: 90</li>
</ul>
</li>
</ul>
</li>
<li><strong>Top Plane</strong>
<ul>
<li><strong>Name</strong>: Top</li>
<li><strong>Position</strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: 5</li>
<li><strong>Z</strong>: 0</li>
</ul>
</li>
<li><strong>Rotation </strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: 180</li>
<li><strong>Z</strong>: 180</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>Your scene should look something similar to what is shown below.</p>
<div id="attachment_3931" class="wp-caption alignnone" style="width: 978px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-1.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-1.png" alt="Unity - Lightmapping (1)" title="Unity - Lightmapping (1)" width="968" height="642" class="size-full wp-image-3931" /></a><p class="wp-caption-text">Unity &#8211; Lightmapping (1)</p></div>
<span id="Add_Some_Color"><h2>Add Some Color</h2></span>
<p>The scene looks pretty boring at this point with no colors.  Let&#8217;s color two of the walls in our room.  We&#8217;ll color the left wall red, and the right wall blue.</p>
<p>Create two new materials.  Name the first material to <strong>Red_Material</strong> and the second material to <strong>Blue_Material</strong></p>
<div id="attachment_3932" class="wp-caption alignnone" style="width: 978px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-2.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-2.png" alt="Unity - Lightmapping (2)" title="Unity - Lightmapping (2)" width="968" height="642" class="size-full wp-image-3932" /></a><p class="wp-caption-text">Unity &#8211; Lightmapping (2)</p></div>
<p>Select the <strong>Red_Material</strong> and set it&#8217;s <strong>Main Color</strong> property to <strong>Red</strong>.</p>
<div id="attachment_3934" class="wp-caption alignnone" style="width: 978px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-3.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-3.png" alt="Unity - Lightmapping (3)" title="Unity - Lightmapping (3)" width="968" height="642" class="size-full wp-image-3934" /></a><p class="wp-caption-text">Unity &#8211; Lightmapping (3)</p></div>
<p>Select the <strong>Blue_Material</strong> and set it&#8217;s <strong>Main Color</strong> property to <strong>Blue</strong>.</p>
<div id="attachment_3936" class="wp-caption alignnone" style="width: 978px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-4.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-4.png" alt="Unity - Lightmapping (4)" title="Unity - Lightmapping (4)" width="968" height="642" class="size-full wp-image-3936" /></a><p class="wp-caption-text">Unity &#8211; Lightmapping (4)</p></div>
<p>Drag-and-Drop the <strong>Red_Material</strong> from the <strong>Project</strong> view onto the <strong>Left</strong> wall.<br />
Drag-and-Drop the <strong>Blue_Material</strong> from the <strong>Project</strong> view onto the <strong>Right</strong> wall.</p>
<div id="attachment_3939" class="wp-caption alignnone" style="width: 978px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-5.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-5.png" alt="Unity - Lightmapping (5)" title="Unity - Lightmapping (5)" width="968" height="642" class="size-full wp-image-3939" /></a><p class="wp-caption-text">Unity &#8211; Lightmapping (5)</p></div>
<p>Place 2 cubes in the scene with the following properties:</p>
<ul>
<li><strong>Cube</strong>
<ul>
<li><strong>Name</strong>: Cube01</li>
<li><strong>Position</strong>
<ul>
<li><strong>X</strong>: 2</li>
<li><strong>Y</strong>: -1.5</li>
<li><strong>Z</strong>: 1</li>
</ul>
</li>
<li><strong>Rotation</strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: 45</li>
<li><strong>Z</strong>: 0</li>
</ul>
</li>
</ul>
</li>
<li><strong>Cube</strong>
<ul>
<li><strong>Name</strong>: Cube02</li>
<li><strong>Position</strong>
<ul>
<li><strong>X</strong>: -2.5</li>
<li><strong>Y</strong>: -3</li>
<li><strong>Z</strong>: 0</li>
</ul>
</li>
<li><strong>Rotation</strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: 0</li>
<li><strong>Z</strong>: 0</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>Your scene should now look something like this:</p>
<div id="attachment_3941" class="wp-caption alignnone" style="width: 978px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-6.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-6.png" alt="Unity - Lightmapping (6)" title="Unity - Lightmapping (6)" width="968" height="642" class="size-full wp-image-3941" /></a><p class="wp-caption-text">Unity &#8211; Lightmapping (6)</p></div>
<p>Save your scene.</p>
<p>Create a yellow material (call it <strong>Yellow_Material</strong>) and place it on <strong>Cube02</strong>.</p>
<div id="attachment_3946" class="wp-caption alignnone" style="width: 978px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-71.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-71.png" alt="Unity - Lightmapping (7)" title="Unity - Lightmapping (7)" width="968" height="642" class="size-full wp-image-3946" /></a><p class="wp-caption-text">Unity &#8211; Lightmapping (7)</p></div>
<p>Now let&#8217;s put a light in the scene.</p>
<span id="Create_a_Light"><h2>Create a Light</h2></span>
<p>Create a <strong>Point light</strong> in the scene with the following properties:</p>
<ul>
<li><strong>Point light</strong>
<ul>
<li><strong>Position</strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: 4.5</li>
<li><strong>Z</strong>: 0</li>
</ul>
</li>
<li><strong>Range</strong>: 12</li>
</ul>
</li>
</ul>
<p>Leave all other properties as the default.</p>
<div id="attachment_3947" class="wp-caption alignnone" style="width: 978px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-8.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-8.png" alt="Unity - Lightmapping (8)" title="Unity - Lightmapping (8)" width="968" height="642" class="size-full wp-image-3947" /></a><p class="wp-caption-text">Unity &#8211; Lightmapping (8)</p></div>
<p>Our scene is looking a little better now with this point light, but I think it can get better.</p>
<span id="Create_the_Lightmap"><h2>Create the Lightmap</h2></span>
<p>Up to this point, we havn&#8217;t done anything that we havn&#8217;t seen before (if you have been following the previous articles then you will already have had some experience placing lights in the scene).  Now we are going to add some realism to the scene by pre-computing the lighting information into a lightmap that is otherwise very difficult to achieve at real-time frame-rates.</p>
<p>Open the <strong>Lightmapping</strong> view (select <strong>Window -> Lightmapping</strong> from the main menu) .</p>
<div id="attachment_3949" class="wp-caption alignnone" style="width: 370px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-Dialog.gif"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-Dialog.gif" alt="Unity - Lightmapping Dialog" title="Unity - Lightmapping Dialog" width="360" height="695" class="size-full wp-image-3949" /></a><p class="wp-caption-text">Unity &#8211; Lightmapping Dialog</p></div>
<p>Click the <strong>Bake</strong> button at the top of the <strong>Lightmapping</strong> view to show the <strong>Bake</strong> settings.</p>
<p>Set the <strong>Mode</strong> to <strong>Single Lightmaps</strong>.</p>
<span id="Single_vs_Dual_Lightmaps"><h3>Single vs Dual Lightmaps</h3></span>
<p><strong>Single</strong> lightmaps will generate a single lightmap for the entire scene.  <strong>Single</strong> lightmaps will generate full lighting information for the lights in your scene that are set to <strong>Auto</strong> or <strong>Baked Only</strong>.  <strong>Single</strong> lightmaps take less time to bake because Beast only needs to generate one set of lightmaps instead of two.  <strong>Single</strong> lightmaps are required when using the forward rendering mode.</p>
<p><strong>Dual</strong> lightmaps are supported for deferred rendering mode.  <strong>Dual</strong> lightmaps will generate two sets of lightmaps; <strong>Near</strong>, and <strong>Far</strong> lightmap sets. The <strong>Near</strong> lightmaps will store indirect lighting information for real-time lights while the direct lighting contributions will be computed from the real-time lights in the scene (unless they are set to <strong>Baked Only</strong>).  The <strong>Far</strong> lightmaps will be baked with both direct and indirect lighting contributions for lights in the scene that are marked <strong>Auto</strong> or <strong>Baked Only</strong>.  <strong>Realtime Only</strong> lights will still be used to compute direct lighting on <strong>Far</strong> objects but dynamic shadows will be disabled.</p>
<p>The transition between the <strong>Near</strong> and <strong>Far</strong> lightmaps is determined by the <strong>Shadow Distance</strong> property in the project&#8217;s <strong>Quality Settings</strong> window (select <strong>Edit -> Project Settings -> Quality</strong> from the main menu).</p>
<p>For the purpose of this exercise, we will only use <strong>Single</strong> lightmaps.</p>
<p>For more information on <strong>Single</strong> and <strong>Dual</strong> lightmaps in Unity, please refer to the Lightmapping In-Depth page on the Unity website here: <a href="http://docs.unity3d.com/Documentation/Manual/LightmappingInDepth.html" title="Lightmapping In-Depth" target="_blank">http://docs.unity3d.com/Documentation/Manual/LightmappingInDepth.html</a>.</p>
<span id="Direct_vs_Indirect_Lighting"><h3>Direct vs Indirect Lighting</h3></span>
<p><strong>Direct</strong> lighting is the light that comes directly from the light source. In reality, when light hits an object, the light will &#8220;bounce&#8221; (or reflect) off of an object&#8217;s surface and it may go on to hit something else.  This &#8220;bounced&#8221; light causes the <strong>indirect</strong> illumination of surfaces around that object.</p>
<p><strong>Indirect</strong> light is the contribution of light that is reflected from surfaces and contributes to the illumination of surfaces in close proximity.  </p>
<p><strong>Indirect</strong> light cannot be simulated using standard rasterization techniques that are generally used to render your game.  But the <strong>indirect</strong> lighting contribution from environment lighting or lighting that is reflected from nearby objects can be simulated by baking this information into a lightmap.  The lightmap generator will use a rendering technique that is well suited for computing the indirect lighting contributions but is not well suited for real-time rendering and therefor this information can be pre-baked into the lightmaps for use at run-time.</p>
<span id="Bake_Settings"><h2>Bake Settings</h2></span>
<p>Open the <strong>Lightmapping</strong> view if it isn&#8217;t open already.</p>
<div id="attachment_3949" class="wp-caption alignnone" style="width: 370px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-Dialog.gif"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-Dialog.gif" alt="Unity - Lightmapping Dialog" title="Unity - Lightmapping Dialog" width="360" height="695" class="size-full wp-image-3949" /></a><p class="wp-caption-text">Unity &#8211; Lightmapping Dialog</p></div>
<p>Set the <strong>Mode</strong> to <strong>Single Lightmaps</strong>.</p>
<p>Set the <strong>Quality</strong> to <strong>High</strong>. The quality setting will determine the overall quality of the generated lightmap.  While you are trying to get the lighting right, it is a good idea to keep this setting at <strong>Low</strong> quality because the lightmap generation will take considerably less time to produce and give a good overall indication of how the high quality lightmaps will look.  When you are satisfied with how the lightmaps look, don&#8217;t forget to change this setting back to <strong>High</strong> and rebake the lightmaps.</p>
<p>Set the <strong>Bounces</strong> to <strong>1</strong>.  Setting the <strong>Bounces</strong> property higher than 0 will enable indirect lighting to be computed on objects. Setting the Bounces property to 0 will cause only direct lighting contributions to be baked into the lightmap.</p>
<p>Set the <strong>Sky Light Intensity</strong> to <strong>0</strong>. We don&#8217;t want to have any skylight contributions added to our lightmap.  Setting this value to <strong>0</strong> effectively disables the <strong>Sky Light</strong>.</p>
<p>Set the <strong>Bounce Boost</strong> and the <strong>Bounce Intensity</strong> values to <strong>2.0</strong>.  This will increase the contribution of indirect light on objects.</p>
<p>Set the <strong>Final Gather Rays</strong> to <strong>1000</strong>.  This value controls the number of Final Gather Rays that are generated at each <strong>Final Gather Point</strong> (see <strong>Contrast Threshold</strong> below). Increasing this value will improve the quality of the final lightmap at the expense of computational cost.  Gernally, 1000 is a good value to use but if you find the quality of the final lightmap is insufficient, then you can increase this value but keep in mind this will have an adverse effect on the time it takes to generate the lightmap.</p>
<p>Set the <strong>Contrast Threshold</strong> to <strong>0.05</strong>. The <strong>Contrast Threshold</strong> value tells Beast how often to generate <strong>Final Gather Points</strong> and thus effecting the total number of <strong>Final Gather Rays</strong> that need to be generated to lightmap the scene. Setting this value lower will cause more <strong>Final Gather Points</strong> to be generated (because the contrast variance required to generate a <strong>Final Gather Point</strong> will be less).  Setting this value higher will cause less <strong>Final Gather Points</strong> to be generated because more contrast variance is required to generate a <strong>Final Gather Point</strong>.  Higher values of Contrast Threshold will generate smother results in the final lightmap at the expense of detail.</p>
<p>Set the <strong>Interpolation</strong> value to <strong>0.5</strong>.  The <strong>Interpolation</strong> value controls the interpolation method used to  interpolate the colors between the <strong>Final Gather Points</strong>.  A value of <strong>0</strong> means a simple linear interpolation between points will be used to determine the intermediate colors.  A value of 1 will give smoother results but can also reduce the detail in the final result.</p>
<p>Set the <strong>Interpolation Points</strong> to <strong>15</strong>. This property controls the number of <strong>Final Gather Points</strong> to interpolate to produce the color at the current pixel in the lightmap.  Higher values can create smoother (more blurred) results at the cost of detail in the lightmap.</p>
<p>Set <strong>Ambient Occlusion</strong> to <strong>0</strong>. <strong>Ambient occlusion</strong> is a rendering technique that approximates the brightness of a pixel based on nearby objects in the scene. It simulates the occlusion of environment lighting due to nearby geometry.  Please refer to Chapter 17 of the GPU Gems text for a complete explanation of Ambient Occlusion (available online here: <a href="http://http.developer.nvidia.com/GPUGems/gpugems_ch17.html" title="Ambient Occlusion" target="_blank">http://http.developer.nvidia.com/GPUGems/gpugems_ch17.html</a></p>
<div id="attachment_3960" class="wp-caption alignnone" style="width: 710px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Ambient-Occlusion.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Ambient-Occlusion.png" alt="Ambient Occlusion" title="Ambient Occlusion" width="700" height="219" class="size-full wp-image-3960" /></a><p class="wp-caption-text">Ambient Occlusion</p></div>
<p>This image shows an application of <strong>Ambient Occlusion</strong>. On the left image, the model is shaded with simple diffuse shading.  The model on the right is shaded with both diffuse shading and ambient occlusion.  Notice the darker areas on the inner thigh of the model and on the ground and around it&#8217;s feet.</p>
<p>Set the <strong>LOD Surface Distance</strong> to <strong>1</strong>.  This property effects the <strong>LOD Group</strong> component that is used to replace high-poly models with low-poly models as the camera moves further away from the <strong>GameObject</strong>.  LOD Groups are only available in the Pro version of Unity, this option may not be available to users of the Free version.</p>
<p>Make sure the <strong>Lock Atlas</strong> option is not checked.  The <strong>Texture Atlas</strong> determines the tiling and offset of objects in the lightmap. Since many objects share the same lightmap, Unity needs to know how much area of an object&#8217;s surface is occupying the lightmap texture.  The <strong>Texture Atlas</strong> is automatically generated every time you bake the lightmaps.  Checking the <strong>Lock Atlas</strong> option will prevent the <strong>Texture Atlas</strong> from being modified and the current tiling and offset settings will be retained for each renderer object (<strong>GameObjects</strong> with a <strong>Mesh Renderer</strong> component attached to them).  You probably want Unity to figure out the <strong>Texture Atlas</strong> for you so you can leave the <strong>Lock Atlas</strong> option unchecked.</p>
<p>Set the <strong>Resolution</strong> property to <strong>50</strong>. This value determines the number of texels per world unit that will be used to generate the lightmaps.  Higher values will generate more detailed lightmaps at the expense of texture memory.  Lower values will generate less detailed lightmaps.</p>
<span id="Make_Objects_Static"><h2>Make Objects Static</h2></span>
<p>Before we can bake the lightmaps, we need to make some geometry static.  Only objects that are marked <strong>Lightmap Static</strong> will be considered during the lightmapping process.</p>
<p>In the <strong>Lightmapping view</strong>, select the <strong>Object</strong> button at the top of the window.</p>
<p>Select the <strong>Renderers</strong> button under <strong>Scene Filters</strong> to show only the GameObjects in the <strong>Hierarchy</strong> view that have a <strong>Mesh Renderer</strong> component attached to them.</p>
<div id="attachment_3967" class="wp-caption alignnone" style="width: 370px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmap-Objects.gif"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmap-Objects.gif" alt="Unity - Lightmap Objects" title="Unity - Lightmap Objects" width="360" height="695" class="size-full wp-image-3967" /></a><p class="wp-caption-text">Unity &#8211; Lightmap Objects</p></div>
<p>Select the <strong>Back</strong>, <strong>Bottom</strong>, <strong>Left</strong>, <strong>Right</strong>, <strong>Top</strong>, <strong>Cube01</strong>, and <strong>Cube02</strong> GameObjects from the <strong>Hierarchy</strong> view.</p>
<div id="attachment_3963" class="wp-caption alignnone" style="width: 978px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-9.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-9.png" alt="Unity - Lightmapping (9)" title="Unity - Lightmapping (9)" width="968" height="642" class="size-full wp-image-3963" /></a><p class="wp-caption-text">Unity &#8211; Lightmapping (9)</p></div>
<p>With all of the static renderers selected in the <strong>Hierarchy</strong> view, make sure the <strong>Static</strong> option is checked in the <strong>Inspector</strong> as shown in the screenshot above.</p>
<p>You should also confirm that the <strong>Lightmap Static</strong> option is checked for your selected object in the <strong>Lightmapping</strong> view, but this should be the case if the object is marked <strong>Static</strong> in the <strong>Inspector</strong>.</p>
<span id="Ligtmapping_Lights"><h2>Ligtmapping Lights</h2></span>
<p>With the <strong>Lightmapping</strong> view open to the <strong>Object</strong> tab, select the <strong>Point light</strong> GameObject in the <strong>Hierarchy</strong> view.</p>
<div id="attachment_3970" class="wp-caption alignnone" style="width: 370px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmap-Objects.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmap-Objects.png" alt="Unity - Lightmap Objects" title="Unity - Lightmap Objects" width="360" height="695" class="size-full wp-image-3970" /></a><p class="wp-caption-text">Unity &#8211; Lightmap Objects</p></div>
<p>Set the <strong>Lightmapping</strong> mode to <strong>Baked Only</strong>. This will ensure the light is considered during the light baking process but the light is ignored at run-time.</p>
<p>Set the <strong>Baked Shadows</strong> property to <strong>On</strong>. It doesn&#8217;t matter if you choose the <strong>On (Realtime: Hard Shadows)</strong> option or the <strong>On (Raltime: Soft Shadows)</strong> option because real-time lighting contributions are ignored on lights that are set to <strong>Baked Only</strong>.</p>
<p>Leave all other settings default and click the <strong>Bake Scene</strong> button on the bottom of the <strong>Lightmapping</strong> window.</p>
<p>The resulting view should look something like this:</p>
<div id="attachment_3972" class="wp-caption alignnone" style="width: 1072px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping.png" alt="Unity - Lightmapping (10)" title="Unity - Lightmapping (10)" width="1062" height="707" class="size-full wp-image-3972" /></a><p class="wp-caption-text">Unity &#8211; Lightmapping (10)</p></div>
<p>This looks better than it did with just a simple point light, but there are still a few issues we can improve.  For example, the shadow edges are very hard. There is no softening of the shadow edges as the shadow surface gets further away from the the object that is casting the shadow.</p>
<p>With the <strong>Point light</strong> selected in the <strong>Hierarchy</strong> view, open the <strong>Lightmapping</strong> view and click the <strong>Object</strong> tab again. </p>
<div id="attachment_3974" class="wp-caption alignnone" style="width: 370px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmap-Objects-11.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmap-Objects-11.png" alt="Unity - Lightmap Objects (11)" title="Unity - Lightmap Objects (11)" width="360" height="695" class="size-full wp-image-3974" /></a><p class="wp-caption-text">Unity &#8211; Lightmap Objects (11)</p></div>
<p>Set the <strong>Shadow Samples</strong> property to <strong>20</strong>.  This value determines the number of shadow rays that are cast to determine if the pixel being rendered is actually in shadow or not.  In reality, light is scattered off of an object&#8217;s surface in an infinite number of directions.  Some of the light scattered off of an object&#8217;s surface will go on to hit another object that does not emit light, but some may also hit something else that emits light.  Obviously, we can&#8217;t simulate an infinite number of scatter rays but we can simulate a fixed number of random ray directions to determine if an object is in light or in shadow.  With only 1 shadow ray being cast, it is likely that a randomly generated ray will be cast in the wrong direction and produce a wrong shadow.  This is why we got blotchy shadows before.  To resolve this, we just need to increase the <strong>Shadow Samples</strong> parameter to allow more shadow rays to be cast from each pixel in the lightmap which will increase the likelihood that the shadows will be computed correctly.</p>
<p>Set the <strong>Shadow Radius</strong> to <strong>0.5</strong>.  The <strong>Shadow Radius</strong> parameter is used to adjust the radius of the currently selected <strong>Point light</strong>.  In reality, no light can possibly have a radius of <strong>0</strong>.  In virtual reality, <strong>Point lights</strong> always have a radius of 0 but this does not produce realistic shadows.  Lights that have a radius larger than 0 are actually called <strong>Area Lights</strong> because they have a surface area greater than 0.  <strong>Area Lights</strong> are required to produce realistic shadows with a soft penumbra (the edge of the shadow that is neither completely in shadow nor completely in the light).  <strong>Point lights</strong> with a radius of 0 will only produce hard shadows in the lightmap even if you select <strong>Soft Shadows</strong> in the <strong>Inspector</strong> view.</p>
<p>Now bake the lightmaps again by pressing the <strong>Bake Scene</strong> button.</p>
<div id="attachment_3975" class="wp-caption alignnone" style="width: 1231px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-12.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-12.png" alt="Unity - Lightmapping (12)" title="Unity - Lightmapping (12)" width="1221" height="803" class="size-full wp-image-3975" /></a><p class="wp-caption-text">Unity &#8211; Lightmapping (12)</p></div>
<p>Now you see that the shadows on the walls and floors are smoother and they also get smoother when the surface in shadow is further away from the shadow caster.</p>
<span id="Emissive_Materials_Pro_Only"><h2>Emissive Materials (Pro Only)</h2></span>
<p>What if we want to make something appear to be glowing, like radioactive slime for example.  For this purpose we could use a self-illuminating material. Also known as an emissive material.</p>
<p>First, let&#8217;s create a self-illuminated material.</p>
<p>Create a new material in the project view and call it &#8220;<strong>Green_Emissive_Material</strong>&#8220;.</p>
<div id="attachment_3981" class="wp-caption alignnone" style="width: 1052px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Emissive-Material.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Emissive-Material.png" alt="Unity - Emissive Material" title="Unity - Emissive Material" width="1042" height="670" class="size-full wp-image-3981" /></a><p class="wp-caption-text">Unity &#8211; Emissive Material</p></div>
<p>Select the new material in the project view and change the <strong>Shader</strong> parameter to &#8220;<strong>Self-Illumin/Diffuse</strong>&#8220;.</p>
<p>Change the <strong>Main Color</strong> to green.</p>
<p>Set the <strong>Emission (Lightmapper)</strong> value to <strong>2</strong>.  This value determines the intensity of the light being emitted from the object.  A value of 0 will not contribute anything to the lightmapping computations.</p>
<p>Add a sphere to your scene with the following properties:</p>
<ul>
<li><strong>Sphere</strong>
<ul>
<li><strong>Static</strong>: True</li>
<li><strong>Position</strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: -2.5</li>
<li><strong>Z</strong>: -2.5</li>
</ul>
</li>
</ul>
</li>
</ul>
<div id="attachment_3984" class="wp-caption alignnone" style="width: 1052px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmap-Objects-13.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmap-Objects-13.png" alt="Unity - Lightmap Objects (13)" title="Unity - Lightmap Objects (13)" width="1042" height="670" class="size-full wp-image-3984" /></a><p class="wp-caption-text">Unity &#8211; Lightmap Objects (13)</p></div>
<p>Drag-and-Drop the <strong>Green_Emissive_Material</strong> onto the <strong>Sphere</strong> in the <strong>Scene</strong> view.</p>
<div id="attachment_3985" class="wp-caption alignnone" style="width: 1052px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmap-Objects-14.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmap-Objects-14.png" alt="Unity - Lightmap Objects (14)" title="Unity - Lightmap Objects (14)" width="1042" height="670" class="size-full wp-image-3985" /></a><p class="wp-caption-text">Unity &#8211; Lightmap Objects (14)</p></div>
<p>Don&#8217;t forget to make sure the sphere is marked as Static!</p>
<p>Save your scene.</p>
<p>Open the <strong>Lightmapping</strong> view and click the <strong>Bake Scene</strong> button.  When the bake is complete, you should see something similar to what is shown below.</p>
<div id="attachment_3987" class="wp-caption alignnone" style="width: 1556px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-with-Self-Illuminating-materials.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Lightmapping-with-Self-Illuminating-materials.png" alt="Unity - Lightmapping with Self-Illuminating materials" title="Unity - Lightmapping with Self-Illuminating materials" width="1546" height="1012" class="size-full wp-image-3987" /></a><p class="wp-caption-text">Unity &#8211; Lightmapping with Self-Illuminating materials</p></div>
<p>Observe the green glow that is emitted from the sphere and illuminating the objects around it.</p>
<p>This works fine for static objects in our scene, but what if we wanted to achieve this glowing effect at run-time on dynamic objects?</p>
<p>Emissive materials (like the one used on the green sphere) cannot be used to emit light onto other objects in the scene dynamically at run-time.  However, we can &#8220;fake&#8221; emissive materials with point lights.</p>
<span id="Emissive_Materials_on_Dynamic_Objects"><h2>Emissive Materials on Dynamic Objects</h2></span>
<p>A similar effect can be achieved with dynamic objects by attaching a <strong>Point light</strong> to the emissive <strong>GameObject</strong>.</p>
<p>Un-check the <strong>Static</strong> flag on the green <strong>Sphere</strong> we just created.  This will prevent the Sphere from being considered for lightmapping. </p>
<p>Attach a <strong>Rigidbody</strong> component to the sphere so that it will be physics controlled.</p>
<p>If the <strong>Sphere </strong>doesn&#8217;t have a <strong>Collider </strong>component, attach a <strong>Sphere Collider</strong> component and set it&#8217;s <strong>Material</strong> property to &#8220;<strong>Bouncy</strong>&#8221; (from the <strong>Physics Materials</strong> standard package).</p>
<p>Add a <strong>Point light</strong> GameObject as a child of the <strong>Sphere</strong> GameObject and set it&#8217;s properties to the following values:</p>
<ul>
<li><strong>Point light</strong>
<ul>
<li><strong>Position</strong>
<ul>
<li><strong>X</strong>: 0</li>
<li><strong>Y</strong>: 0</li>
<li><strong>Z</strong>: 0</li>
</ul>
</li>
<li><strong>Type</strong>: Point</li>
<li><strong>Color</strong>: Green</li>
<li><strong>Render Mode</strong>: Important</li>
<li><strong>Lightmapping</strong>: Realtime Only</li>
</ul>
</li>
</ul>
<p>Setting the light&#8217;s <strong>Render Mode</strong> property to <strong>Important</strong> will make sure it&#8217;s rendered with per-pixel lighting and setting the <strong>Lightmapping</strong> property to <strong>Realtime Only</strong> will ensure that it is not considered when generating the lightmap (which it won&#8217;t if we unchecked the <strong>Static</strong> flag).</p>
<p>You should see something similar to what is shown below.</p>
<p><iframe width="640" height="360" src="http://www.youtube.com/embed/IazXxXRFtz0?rel=0" frameborder="0" allowfullscreen></iframe></p>
<span id="Conclusion"><h1>Conclusion</h1></span>
<p>In this article, you have been introduced to cameras, lights, materials and lightmapping in Unity.  We have seen how we can use Self-Illuminating materials in our scene to create apparently glowing objects in the lightmap and I&#8217;ve also shown a technique that can be used to &#8220;fake&#8221; this effect in real-time (at the expense of GPU processing power).</p>
<span id="Resources"><h1>Resources</h1></span>
<p>Most of the content for this article has been derived from various sources in the Component Reference documentation on the Unity website:</p>
<p><a href="http://docs.unity3d.com/Documentation/Components/index.html" title="Unity Component Reference" target="_blank">http://docs.unity3d.com/Documentation/Components/index.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://3dgep.com/?feed=rss2&#038;p=3856</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Scripting in Unity 3.5</title>
		<link>http://3dgep.com/?p=3474</link>
		<comments>http://3dgep.com/?p=3474#comments</comments>
		<pubDate>Wed, 05 Sep 2012 21:11:07 +0000</pubDate>
		<dc:creator>Jeremiah van Oosten</dc:creator>
				<category><![CDATA[Unity]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Scripts]]></category>

		<guid isPermaLink="false">http://3dgep.com/?p=3474</guid>
		<description><![CDATA[In this article, I will introduce you to scripting in Unity 3.5. Unity is a powerful game editor that only limits you to what you can imagine. Scripting is where the magic happens which will bring your games to life. <a href="http://3dgep.com/?p=3474">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="attachment_3850" class="wp-caption alignleft" style="width: 160px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Logo-3-512x512.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Logo-3-512x512-150x150.png" alt="Unity - Scripting" title="Unity - Scripting" width="150" height="150" class="size-thumbnail wp-image-3850" /></a><p class="wp-caption-text">Unity &#8211; Scripting</p></div>
<p>In this article, I will introduce you to scripting in Unity 3.5. Unity is a powerful game editor that only limits you to what you can imagine. Scripting is where the magic happens which will bring your games to life. I assume the reader is familiar the Unity interface, if not you can refer to my previous article titled <a href="http://3dgep.com/?p=3246" title="Introduction to Unity">Introduction to Unity</a> (<a href="http://3dgep.com/?p=3246" title="Introduction to Unity">http://3dgep.com/?p=3246</a>).</p>
<p>This article is intended for designers and artists who have no previous programming experience. For this reason, I will go into details about JavaScript syntax that the experienced programmer may find boring.</p>
<p><span id="more-3474"></span></p>
<div style="clear: both;"><div class='toc wptoc'>
<h2>Table of Contents</h2>
<ol class='toc-odd level-1'>
	<li>
		<a href="#Introduction">Introduction</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#JavaScript">JavaScript</a>
			</li>
			<li>
				<a href="#C">C#</a>
			</li>
			<li>
				<a href="#Boo">Boo</a>
			</li>
		</ol>
	<li>
		<a href="#JavaScript_Basics">JavaScript Basics</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Creating_Scripts">Creating Scripts</a>
			</li>
			<li>
				<a href="#The_Game_Loop">The Game Loop</a>
				<ol class='toc-odd level-3'>
					<li>
						<a href="#Update_Loop">Update Loop</a>
					</li>
					<li>
						<a href="#Fixed_Update_Loop">Fixed Update Loop</a>
					</li>
					<li>
						<a href="#The_OnRenderObject_Method">The OnRenderObject Method</a>
					</li>
				</ol>
			<li>
				<a href="#Variables">Variables</a>
			</li>
			<li>
				<a href="#Types">Types</a>
				<ol class='toc-odd level-3'>
					<li>
						<a href="#Integer">Integer</a>
					</li>
					<li>
						<a href="#Float">Float</a>
					</li>
					<li>
						<a href="#Double">Double</a>
					</li>
					<li>
						<a href="#Strings">Strings</a>
					</li>
					<li>
						<a href="#Boolean">Boolean</a>
					</li>
					<li>
						<a href="#Arrays">Arrays</a>
						<ol class='toc-even level-4'>
							<li>
								<a href="#Built-In_Array">Built-In Array</a>
							</li>
							<li>
								<a href="#JavaScript_Array">JavaScript Array</a>
							</li>
							<li>
								<a href="#Accessing_Array_Elements">Accessing Array Elements</a>
							</li>
						</ol>
					<li>
						<a href="#Class">Class</a>
					</li>
				</ol>
			<li>
				<a href="#Rotation_Script">Rotation Script</a>
			</li>
			<li>
				<a href="#Time">Time</a>
			</li>
			<li>
				<a href="#Conditional_Logic">Conditional Logic</a>
				<ol class='toc-odd level-3'>
					<li>
						<a href="#Boolean_Logic">Boolean Logic</a>
						<ol class='toc-even level-4'>
							<li>
								<a href="#If_Statement">If Statement</a>
							</li>
							<li>
								<a href="#If-Then-Else">If-Then-Else</a>
							</li>
							<li>
								<a href="#Switch_Statement">Switch Statement</a>
							</li>
							<li>
								<a href="#While_Loops">While Loops</a>
							</li>
							<li>
								<a href="#Do-While_Loops">Do-While Loops</a>
							</li>
							<li>
								<a href="#For_Loops">For Loops</a>
							</li>
							<li>
								<a href="#For-In_Loop">For-In Loop</a>
							</li>
						</ol>
</ol>
</ol>
					<li>
						<a href="#Wall_Breaker">Wall Breaker</a>
						<ol class='toc-even level-2'>
							<li>
								<a href="#Create_A_New_Scene">Create A New Scene</a>
							</li>
							<li>
								<a href="#Create_A_Plane">Create A Plane</a>
							</li>
							<li>
								<a href="#Create_a_Brick">Create a Brick</a>
							</li>
							<li>
								<a href="#Create_a_Canon_Ball_Prefab">Create a Canon Ball Prefab</a>
							</li>
							<li>
								<a href="#Adding_the_Logic">Adding the Logic</a>
								<ol class='toc-odd level-3'>
									<li>
										<a href="#The_Start_Function">The Start Function</a>
									</li>
									<li>
										<a href="#The_Update_Function">The Update Function</a>
									</li>
								</ol>
							<li>
								<a href="#Adding_the_Logic_to_the_Scene">Adding the Logic to the Scene</a>
							</li>
							<li>
								<a href="#Tweaking_and_Polish">Tweaking and Polish</a>
							</li>
							<li>
								<a href="#Playing_your_Game">Playing your Game</a>
							</li>
						</ol>
					<li>
						<a href="#Conclusion">Conclusion</a>
					</li>
					<li>
						<a href="#References">References</a>
					</li>
</ol>
</div>
<div class='wptoc-end'>&nbsp;</div></div>
<span id="Introduction"><h1>Introduction</h1></span>
<p>The Unity game engine supports the ability to program game behaviours using a variaty of scripting languages.  The primary scripting languages supported by Unity are JavaScript, C#, and a dialect of Python called Boo.</p>
<p>Unity has full support for the .NET 2.0 framework when deploying your game as a desktop application and a subset of the .NET 2.0 framework when deploying as a web player or mobile device.</p>
<span id="JavaScript"><h2>JavaScript</h2></span>
<div id="attachment_3705" class="wp-caption alignleft" style="width: 160px"><a href="http://3dgep.com/wp-content/uploads/2012/08/JavaScript-Icon.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/JavaScript-Icon-150x150.png" alt="JavaScript Icon" title="JavaScript Icon" width="150" height="150" class="size-thumbnail wp-image-3705" /></a><p class="wp-caption-text">JavaScript Icon</p></div>
<p>JavaScript is an easy to use, easy to learn scripting language and the primary scripting language used in this article.</p>
<p>JavaScript has a similar syntax to the Java programming language which is also similar to C++ style programming.  It&#8217;s my recommended language for people who don&#8217;t have much programming experience.</p>
<span id="C"><h2>C#</h2></span>
<div id="attachment_3706" class="wp-caption alignleft" style="width: 160px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Visual-C-Icon.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Visual-C-Icon-150x150.png" alt="Visual C# Icon" title="Visual C# Icon" width="150" height="150" class="size-thumbnail wp-image-3706" /></a><p class="wp-caption-text">Visual C# Icon</p></div>
<p>C# can be considered a &#8220;Programming Language&#8221; more than a scripting language. It can be used to create stand-alone applications using Microsoft&#8217;s .NET Framework.  </p>
<span id="Boo"><h2>Boo</h2></span>
<div id="attachment_3707" class="wp-caption alignleft" style="width: 160px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Boo-Icon.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Boo-Icon-150x150.png" alt="Boo Icon" title="Boo Icon" width="150" height="150" class="size-thumbnail wp-image-3707" /></a><p class="wp-caption-text">Boo Icon</p></div>
<p>Boo is a scripting language that is inspired by the popular Python scripting language.  Although Boo is not widely used in Unity, it is one of the standard scripting languages supported by the Mono development API so naturally, it is supported by Unity as well.</p>
<div style="clear: both;">&nbsp;</div>
<p>In this article, I will focus on creating scripts using the JavaScript scripting language.</p>
<span id="JavaScript_Basics"><h1>JavaScript Basics</h1></span>
<p>Instead of simply writing JavaScript reference documentation, I will try to teach JavaScript by showing a series of examples that slowly build-up your knowledge of the JavaScript scripting language and how it is used in Unity.</p>
<p>If you haven&#8217;t done so already, launch your Unity editor and create a new empty project.  If you are unsure how to get started with Unity, you can refer to my previous article titled <a href="http://3dgep.com/?p=3246" title="Introduction to Unity 3.5">Introduction to Unity</a>.  If you just want to skip to the part about creating your first project, click <a href="http://3dgep.com/?p=3246#Creating_Your_First_Project" title="Introduction to Unity - Creating Your First Project" target="_blank">here</a>.</p>
<span id="Creating_Scripts"><h2>Creating Scripts</h2></span>
<p>If you created a new empty project, you should have a screen that looks something like the image below.</p>
<div id="attachment_3714" class="wp-caption alignnone" style="width: 993px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Empty-Project.gif"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Empty-Project.gif" alt="Unity - Empty Project" title="Unity - Empty Project" width="983" height="667" class="size-full wp-image-3714" /></a><p class="wp-caption-text">Unity &#8211; Empty Project</p></div>
<p>In the <strong>Project View</strong> create a new <strong>Folder</strong> called <strong>&#8220;Scripts&#8221;</strong>.  Inside the Scripts folder, create a new folder called <strong>&#8220;JavaScript&#8221;</strong>.  Your project view should look something like the image shown below.</p>
<div id="attachment_3715" class="wp-caption alignnone" style="width: 241px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Project-View-2.gif"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Project-View-2.gif" alt="Unity - Project View" title="Unity - Project View" width="231" height="265" class="size-full wp-image-3715" /></a><p class="wp-caption-text">Unity &#8211; Project View</p></div>
<p>Right-click on the <strong>&#8220;JavaScript&#8221;</strong> folder and select <strong>Create -> Javascript</strong> from the pop-up menu that appears.</p>
<p>Give the new script asset an interesting name like <strong>&#8220;HelloWorld&#8221;</strong> (Unity will add the &#8220;.js&#8221; extension for you automatically so you don&#8217;t have to add it in the file name here).</p>
<p>If you select the new JavaScript asset in the <strong>Project</strong> view, you will see the contents of the JavaScript file in the <strong>Inspector</strong> view.</p>
<div id="attachment_3719" class="wp-caption alignnone" style="width: 486px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-JavaScript-Import-Settings.gif"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-JavaScript-Import-Settings.gif" alt="Unity - JavaScript Import Settings" title="Unity - JavaScript Import Settings" width="476" height="419" class="size-full wp-image-3719" /></a><p class="wp-caption-text">Unity &#8211; JavaScript Import Settings</p></div>
<p>Press the <strong>&#8220;Open&#8230;&#8221;</strong> button on the Inspector view.</p>
<p>Unity comes with a built-in source code editor called <strong>MonoDevelop-Unity</strong> which is a customized version of the <strong>MonoDevelop</strong> source code editor.  By default, the MonoDevelop-Unity editor will open and your &#8220;HelloWorld.js&#8221; script should open and you should see something similar to what is shown below.</p>
<div id="attachment_3723" class="wp-caption alignnone" style="width: 1089px"><a href="http://3dgep.com/wp-content/uploads/2012/08/MonoDevelop-HelloWorld.gif"><img src="http://3dgep.com/wp-content/uploads/2012/08/MonoDevelop-HelloWorld.gif" alt="MonoDevelop - HelloWorld" title="MonoDevelop - HelloWorld" width="1079" height="719" class="size-full wp-image-3723" /></a><p class="wp-caption-text">MonoDevelop &#8211; HelloWorld</p></div>
<p>When you create a new JavaScript source file, Unity will provide some default template for you.  Let&#8217;s take a look at what Unity provides by default.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="HelloWorld.js">
#pragma strict

function Start () {

}

function Update () {

}
</pre>
</div>
<p>So this is not very interesting, but let&#8217;s take a look at what this script is doing.</p>
<p>On the first line you see <strong>&#8220;#pragma strict&#8221;</strong>.  This is a special command (called a compiler directive) that is used to tell the JavaScript compiler to not allow dynamic typing in this script file.  Basically this is an optimization that will allow your script to run faster.  You should always use this command at the top of every JavaScript file.</p>
<div class="my-note">
The observant programmer will realize that this compiler directive is only available in JavaScript source files and not in C# or Boo scripts.  This is because JavaScript has support for dynamic typing but this directive disables dynamic typing in this script file.</p>
<p>C# and Boo are statically typed languages and therefor this directive is always implied.
</p></div>
<p>On line 3 a <strong>function</strong> called <strong>Start</strong> is defined.</p>
<p>A <strong>function</strong> is a group of commands that can be executed many times without having to rewrite any code.  That <strong>function</strong> can be executed by accessing the name of the function.  </p>
<p>For example, we could create a <strong>function</strong> called <strong>Jump</strong> in our script and anytime the user presses the &#8220;Jump&#8221; key on the keyboard or game controller, we would invoke the <strong>function</strong> that executes the group of commands that makes our character jump.  Without functions, we would have to rewrite all of the commands needed to execute that action everywhere it is used.  Imagine how difficult it becomes to keep this action the same everywhere it is used!</p>
<p>In this case, the <strong>Start</strong> function in this script is invoked when the game is started.</p>
<p>On line 7 another function called <strong>Update</strong> is declared.  This function is called by the Unity engine on the script every time the game loop is ticked.</p>
<p>Before we go further, let&#8217;s take a look at what the game loop is.</p>
<span id="The_Game_Loop"><h2>The Game Loop</h2></span>
<p>The game loop is a sequence of events that occur during  the lifetime of your game. It usually starts off with some kind of initialization sequence, followed by an infinite (until the game is quit) loop which when terminated, is followed by some termination sequence.  Which might look something like this:</p>
<div id="attachment_3729" class="wp-caption alignnone" style="width: 630px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Game-Flow.gif"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Game-Flow.gif" alt="Unity Game Flow Diagram" title="Unity Game Flow Diagram" width="620" height="640" class="size-full wp-image-3729" /></a><p class="wp-caption-text">Unity Game Flow Diagram</p></div>
<p>When the player starts the game, the script components that are attached to the GameObject&#8217;s in the scene are loaded.  When the script is loaded, it&#8217;s <strong>Awake()</strong> method is invoked (if it has been defined on the script).</p>
<p>If there are any statements defined in the global scope, then these statements are executed just before the <strong>Start()</strong> function is called for each <strong>GameObject</strong>. </p>
<p>The <strong>Start()</strong> function is called after all of the <strong>GameObjects</strong> in the scene have been loaded but before the first call to <strong>Update()</strong> or <strong>FixedUpdate()</strong> method.  The <strong>Start()</strong> function is the best place to query for references to other <strong>GameObjects</strong> in the scene because when <strong>Start()</strong> is called, you know that all other <strong>GameObjects</strong> have been loaded.</p>
<p>After the <strong>Start()</strong> function returns, the game enters the main update loop.  The update loop is executed indefinitely until the game is quit.  There are actually 2 update loops in Unity.  The main update loop and the fixed-time update loop.</p>
<span id="Update_Loop"><h3>Update Loop</h3></span>
<p>The main update loop is executed as fast as possible regardless of processing power or complexity of the game logic.  This means that this Update loop may execute more times per second on computers with faster CPU&#8217;s and less times per second on computers with slower CPU&#8217;s than your own.</p>
<p>This Update Loop may look something like the diagram shown below.</p>
<div id="attachment_3731" class="wp-caption alignnone" style="width: 560px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Update-Loop.gif"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Update-Loop.gif" alt="Unity Update Loop" title="Unity Update Loop" width="550" height="446" class="size-full wp-image-3731" /></a><p class="wp-caption-text">Unity Update Loop</p></div>
<p>From the diagram, we can see that unless the user has quit the game, the <strong>Update()</strong> function will be called on all enabled script components in the scene that define the function.  </p>
<p>After all script components have been updated, the <strong>LateUpdate()</strong> function is called.  The <strong>LateUpdate()</strong> function can be used when you want to make sure that all <strong>GameObjects</strong> in the scene have been updated first before you do something else.</p>
<span id="Fixed_Update_Loop"><h3>Fixed Update Loop</h3></span>
<p>The <strong>FixedUpdate()</strong> function is executed at a fixed time step.  You can configure the time between calls to <strong>FixedUpdate()</strong> in the project settings but generally you can leave the setting at it&#8217;s default value.</p>
<p>It is recommended to use the <strong>FixedUpdate()</strong> method rather than the <strong>Update()</strong> method to control things that effect physics objects (like the Rigidbody component) because this function is guaranteed to execute at a fixed time-step.  When you can guarantee the time-step between frames, your simulations will be more stable and more predictable (and more reproducible) than if the time-step between frames is variable.</p>
<p>The flow diagram for the fixed update loop might look something like the image shown below.</p>
<div id="attachment_3733" class="wp-caption alignnone" style="width: 516px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Fixed-Update-Loop.gif"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Fixed-Update-Loop.gif" alt="Unity Fixed Update Loop" title="Unity Fixed Update Loop" width="506" height="430" class="size-full wp-image-3733" /></a><p class="wp-caption-text">Unity Fixed Update Loop</p></div>
<p>As you can see from the diagram, as long as the user hasn&#8217;t quit the game and the fixed-timestep time has elapsed, execute the <strong>FixedUpdate()</strong> function.</p>
<p>We can test the execution order of these functions with the following script:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="ExecutionOrder.js">
#pragma strict

Debug.Log("ExecutionOrder::global");

function Awake() {
	Debug.Log("ExecutionOrder::Awake");	
}

function Start () {
	Debug.Log("ExecutionOrder::Start");
}

function Update () {
	Debug.Log("ExecutionOrder::Update");
}

function FixedUpdate() {
	Debug.Log("ExecutionOrder::FixedUpdate");
}

function LateUpdate() {
	Debug.Log("ExecutionOrder::LateUpdate");
}

function OnRenderObject() {
	Debug.Log("ExecutionOrder::OnRenderObject");
}
</pre>
</div>
<p>Copy this code to a new <strong>Javascript</strong> asset (called <strong>&#8220;ExecutionOrder&#8221;</strong> for example) then drag-and-drop this script asset onto one <strong>GameObject</strong> in the scene.</p>
<p>Open the <strong>Console</strong> window (Ctrl-Shift-C) and play the game for about 1-2 seconds.  You should see the following statements in the <strong>Console</strong> window.</p>
<pre>
ExecutionOrder::Awake
ExecutionOrder::global
ExecutionOrder::Start
ExecutionOrder::FixedUpdate
ExecutionOrder::Update
ExecutionOrder::LateUpdate
ExecutionOrder::FixedUpdate
ExecutionOrder::Update
ExecutionOrder::LateUpdate
ExecutionOrder::OnRenderObject
...
</pre>
<p>From this output you can confirm that the <strong>Awake()</strong> function is called first, then the statements in the <strong>global</strong> section are executed followed by the <strong>Start()</strong> function.  Thereafter the <strong>Update</strong> and <strong>FixedUpdate</strong> loops are entered.  Whether the <strong>Update()</strong> method or the <strong>FixedUpdate()</strong> method are invoked first or how many times <strong>Update()</strong> is called compared to <strong>FixedUpdate()</strong> is not strictly guaranteed.</p>
<span id="The_OnRenderObject_Method"><h3>The OnRenderObject Method</h3></span>
<p>The <strong>OnRenderObject()</strong> function is invoked after the camera has rendered the scene but before the rendered scene is displayed on the screen.  So this function could be used to render a mesh or other geometry after everything else in the scene has been rendered.  For example, you could use this function to draw a silhouette or highlight around any geometry even if it&#8217;s occluded by other geometry in the scene (x-ray vision?)</p>
<p>If you look at the output from the previous example, you may notice that the <strong>OnRenderObject()</strong> function is not necessarily invoked after every <strong>Update()</strong> function.  This implies that the game is <strong>Updated</strong>  as fast as possible, but the scene is only <strong>Rendered</strong> when the screen needs to be redrawn (based on the refresh rate of your screen but usually 60 frames/second).</p>
<span id="Variables"><h2>Variables</h2></span>
<p>Of course, it would be difficult to implement any interesting behaviours if we only had functions.  We need something else to store the current <strong>State</strong> of our <strong>GameOjects</strong>.  For this, we use <strong>variables</strong>.</p>
<p>A variable is something that can hold data.</p>
<p>A variable declaration has the following form in JavaScript</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var variableName [: type] [= value];
</pre>
</div>
<p>The <strong>var</strong> keyword is required when declaring variables (similar to the <strong>function</strong> keyword when you declare a function).  The <strong>var</strong> keyword is always follwed by the <strong>variable name</strong>.</p>
<p>A variable name must always begin with a letter (&#8216;a&#8217;-'Z&#8217;) or an underscore (&#8216;_&#8217;) followed by any combinations of letters (&#8216;a&#8217;-'Z&#8217;), numbers (&#8217;0&#8242;-&#8217;9&#8242;), or underscore (&#8216;_&#8217;) characters.  Variable names may not contain spaces.</p>
<p>For example, the following variable declarations are valid:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var a;         // OK: Single letter variables are okay,
               //  but not recommended.
var b;         // OK: variable names should be more meaningful.
var a0;        // OK: Starts with a letter follwed by a number.

var _rotation; // OK: Starts with an underscore
var Rotation;  // OK: Starts with a capital letter
var rotation;  // OK: Variable names are case-sensitive so 
               //   Rotation is different from rotation.
</pre>
</div>
<p>The following declarations are not valid:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var 123;           // ERROR: Starts with a number.
var 123a;          // ERROR: Starts with a number.
var &#64;foo;          // ERROR: &#64; is not a valid character.
var rotation rate; // ERROR: Variable names cannot contain spaces.
var var;           // ERROR: Variable names cannot be reserved keywords.
</pre>
</div>
<p>Optionally, you can assign a value to the variable in the variable declaration.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var foo = 5;                  // foo is an integer.
var bar = 5.0f;               // bar is a floating-point value.
var token = 'a';              // token is a character.
var message = "Hello World!"; // message is a string.
var isFun = false;            // isFun is a boolean.
</pre>
</div>
<p>JavaScript uses type inference which means that the JavaScript compiler can infer the type of the variable based on its value.  In this case, you don&#8217;t have to explicitly declare the type.  In the example above, the value <strong>foo</strong> becomes an integer (<strong>int</strong>), <strong>bar</strong> becomes a floating-point value (<strong>float</strong>), <strong>token</strong> becomes a character (char),<strong>message</strong> becomes a string of characters (<strong>string</strong>), and <strong>isFun</strong> becomes a <strong>boolean</strong>.</p>
<span id="Types"><h2>Types</h2></span>
<p>Optionally, you can also explicitly specify the variable <strong>type</strong> when you declare a variable.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="Script.js">
var foo : int;         // foo is explicitly an integer.
var bar : float;       // bar is explicitly a floating-point value.
var message : String;  // message is explicitly a character string.
var isFun : boolean;   // isFun is explicitly a boolean.
</pre>
</div>
<p>Let&#8217;s examine the different primitive types that are supported in <strong>JavaScript</strong>.</p>
<span id="Integer"><h3>Integer</h3></span>
<p>An integer is declared using the <strong>int</strong> type in JavaScript.  An integer is implemented as a <strong>System.Int32</strong> in the .NET Framework.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var foo : int;
</pre>
</div>
<p>An integer (<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?\mathbb{Z}" style="float:top;" border="0px" />) can be used to store any positive or negative whole number.  It cannot be used to store numbers with a decimal points.</p>
<p>Integers can be in the range -2,147,483,648 to 2,147,483,647.</p>
<span id="Float"><h3>Float</h3></span>
<p>A floating-point value is declared with the <strong>float</strong> type in JavaScript.  The <strong>float</strong> type is implemented as a <strong>System.Single</strong> in the .NET Framework.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var bar : float;
</pre>
</div>
<p>A floating-point value is a Real (<img src="http://igad1.nhtv.nl/cgi-bin/mathtex.cgi?\mathbb{R}" style="float:top;" border="0px" />) number. Real numbers can be used to represent values that occur in-between the whole numbers but it can also be used to represent whole numbers.</p>
<p>For example, the following values are all valid single-precision floating-point numbers:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var foo = 3.14159265359f; //  PI
var bar = 0.5f;           //  1/2
var fooBar = -0.5f;       // -1/2
var fooFoo = 5.0f;        //  5
</pre>
</div>
<p>The &#8220;<strong>f</strong>&#8221; post-fix on the value tells the compiler that the number represents a single-precision 32-bit floating-point value.  This post-fix is optional in JavaScript.</p>
<p>A single-precision 32-bit floating-point value can be in the range -3.402823e<sup>38</sup> to 3.402823e<sup>38</sup>.</p>
<span id="Double"><h3>Double</h3></span>
<p>If the single-precision 32-bit floating-point value is not accurate enough for you (99.99% of the time, a float has enough precision), then you can use a double-precision 64-bit floating-point value (double).  A double is implemented as a <strong>System.Double</strong> in the .NET Framework.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var bar : double;
</pre>
</div>
<p>For example, the following variable declarations are valid double-precision floating-point values:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var foo : double = 3.1415926535897932384626433832795; //  PI
var bar : double = 0.5;           //  1/2
var fooBar : double = -0.5;       // -1/2
var fooFoo : double = 5.0;        //  5
</pre>
</div>
<p>If you really want a double, you should explicitly declare the type for the variable otherwise it will be declared as a single-precision 32-bit floating point value (float).</p>
<p>A double-precision 64-bit floating-point value can be in the range -1.79769313486232e<sup>308</sup> to 1.79769313486232e<sup>308</sup></p>
<div class="my-note">
It is recommended that you only use single-precision 32-bit floating-point values (float) in your game.  In most cases these values provide enough precision for your needs.</p>
<p>Double-precision 64-bit floating-point values will run slower than single-precision 32-bit floating point values when deploying to 32-bit builds and they also consume twice as much space in memory.</p>
<p>It is recommended to only use doubles when absolutely necessary.
</p></div>
<span id="Strings"><h3>Strings</h3></span>
<p>A <strong>string</strong> is used to store a character string.  A character string is any sequence of characters enclosed in double-quotes or single-quote characters.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var bar : String;
</pre>
</div>
<p>A String is implemented as a <strong>System.String</strong> in the .NET Framework.</p>
<p>For example, the following string declarations are all valid.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var playerName = "Jeremiah";
var message = "Hello, my name is \"Jeremiah\"";
var quote = '"To be or not to be..."';
</pre>
</div>
<p>These three strings demonstrate some interesting syntax rules.  The first string (<strong>&#8220;Jeremiah&#8221;</strong>) is a simple double-quoted string.  This is probably the most common type you will use.  </p>
<p>The second string on line 2 is a double-quoted string that contains the double-quote character inside the string.  In this case, we must escape the double-quote character inside the string with the back-slash character (&#8216;<strong>\</strong>&#8216;).</p>
<p>The third string on line 3 is a single-quoted string that contains the double-quote character inside the string.  In this case we do not need to use the escape character (&#8216;<strong>\</strong>&#8216;) to insert the double-quote character.</p>
<p>The table below shows the different escape sequences that can be used in strings.</p>
<table width="100%" border="0">
<tr>
<th width="160" nowrap="nowrap">Escape Sequence</th>
<th>Effect</th>
</tr>
<tr>
<td nowrap="nowrap">\b</td>
<td>Backspace (rarly used)</td>
</tr>
<tr>
<td nowrap="nowrap">\f</td>
<td>Form feed (rarly used)</td>
</tr>
<tr>
<td nowrap="nowrap">\n</td>
<td>Newline. A newline character will be inserted and the text will wrap to the next line.</td>
</tr>
<tr>
<td nowrap="nowrap">\r</td>
<td>Carriage return. Traditionally used to move the position of the cursor to the beginning of the current line. This escape sequence is generally not used.</td>
</tr>
<tr>
<td nowrap="nowrap">\&#8217;</td>
<td>Single quote. Used in single-quoted strings to insert the single-quote character. It is not necessary to use this escape sequence in double-quoted strings.</td>
</tr>
<tr>
<td nowrap="nowrap">\&quot;</td>
<td>Double quote. Used in double-quoted strings to insert the double-quote character. It is not necessary to use this escape sequence in single-quoted strings.</td>
</tr>
<tr>
<td nowrap="nowrap">\\</td>
<td>Backslash character. Used to insert the backslash character.</td>
</tr>
</table>
<p>Strings can be concatenated together using the &#8216;<strong>+</strong>&#8216; operator.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var string1 = "Hello";
var string2 = "World!";
var concatString = string1 + " " + string2;
</pre>
</div>
<p>The <strong>concatString</strong> variable will contain the string &#8220;Hello World!&#8221;.</p>
<span id="Boolean"><h3>Boolean</h3></span>
<p>A <strong>boolean</strong> is logic data type that can have 1 of 2 possible values: <strong>true</strong> or <strong>false</strong>.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var bar : boolean;
</pre>
</div>
<p>The <strong>boolean</strong> type is implemented as the <strong>System.Boolean</strong> type in the .NET Framework.</p>
<p>Some valid values for the boolean data types are:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var isTrue = true;    // Value is true.
var isFalse = false;  // Value is false. (This is a bad name for this variable!)
</pre>
</div>
<p>The variable name &#8220;isFalse&#8221; is actually a really bad name for a boolean value. Can you explain why?</p>
<span id="Arrays"><h3>Arrays</h3></span>
<p>What do you do if you need to declare a lot of things of the same type but you don&#8217;t want to declare a separate variable for each one?  You use <strong>arrays</strong>.</p>
<p>There are multiple ways to declare an array in JavaScript.</p>
<span id="Built-In_Array"><h4>Built-In Array</h4></span>
<p>The built-in array is the preferred way to declare an array. It&#8217;s the fastest way to access elements sequentially in script.</p>
<p>A built-in array is declared in the following way:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var floatArray : float[]; // Un-sized static array.
</pre>
</div>
<p>The statement above will declare an un-sized array of floats.  Using this method of declaring an array requires the user to populate the array in the <strong>Inspector</strong>.  This array cannot be re-sized in script.</p>
<h4>Literal Array<br />
<h4>
<p>You can also initialize an array with literal values during declaration.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var floatArray = [ 1.0f, 2.0f, 3.0f ]; // Static array with 3 values.
</pre>
</div>
<p>In this case, a 3-element array is created with its first element initialized to 1.0f, the second element initialized to 2.0f, and the third to 3.0f.  Using this method, the array can only be resized in the <strong>Inspector</strong>. This array cannot be re-sized in script but you should also not assume the array contains any values at all because the user can set the number of elements in this array to 0 in the <strong>Inspector</strong> if they want.</p>
<span id="JavaScript_Array"><h4>JavaScript Array</h4></span>
<p>Unity provides the JavaScript array type to be consistent with standard JavaScript syntax.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var javascriptArray = new Array(); // JavaScript Array
</pre>
</div>
<p>A JavaScript array is not actually an array at all but rather an <strong>Object</strong> that behaves like an array.</p>
<p>JavaScript arrays are not exposed in the <strong>Inspector</strong> but they can be dynamically sized in script.</p>
<p>JavaScript arrays can be converted to built-in arrays by using the <strong>ToBuiltin</strong> function on the JavaScript array object.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var builtinArray : String[] = javascriptArray.ToBuiltin(String);
</pre>
</div>
<span id="Accessing_Array_Elements"><h4>Accessing Array Elements</h4></span>
<p>Regardless of type of array the individual array elements are accessed in the same way.  To refer to a particular element of the array you use the index of the element in the array enclosed in square brackets (<strong>[ ]</strong>).  The first array element is at index <strong>0</strong> and the second array element is at index <strong>1</strong> etc&#8230;</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var stringArray = new String[5];

stringArray[0] = "Hello, ";
stringArray[1] = "my ";
stringArray[2] = "name ";
stringArray[3] = "is ";
stringArray[4] = "Jeremiah ";
</pre>
</div>
<p>We can query the number of elements in an array using the <strong>Length</strong> property of the array.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:9;">
Debug.Log( "The stringArray contains " + stringArray.Length + " elements." );
</pre>
</div>
<p>The previous line will print &#8220;The stringArray contains 5 elements.&#8221;.</p>
<span id="Class"><h3>Class</h3></span>
<p>A <strong>Class</strong> is a complex type that can contain both variables and functions.  Classes are declared using the <strong>class</strong> keyword.</p>
<p>A class is not the same as a variable.  You cannot assign values to the member variables of a class unless you first create an instance of that class.  Let&#8217;s take a look at an example.</p>
<p>Suppose we declare a class called &#8220;<strong>Person</strong>&#8220;:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="Objects.js">
class Person
{
	var firstName : String;
	var lastName : String;
	var age : int;
	var isMale : boolean;
}
</pre>
</div>
<p>The <strong>Person</strong> class contains four member variables (<strong>firstName</strong>, <strong>lastName</strong>, <strong>age</strong>, and <strong>isMale</strong>).</p>
<p>We can create an instance of the class by declaring a variable of the class type.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:9;" title="Objects.js">
var person : Person;  // Declare a variable of type Person.
                      // Identifier names are case-sensitive so
                      // person and Person are two different things!
var jeremiah = new Person(); // Create a new instance of a Person.

jeremiah.firstName = "Jeremiah"; // OK: jeremiah is an instance of Person.
person.firstName = "First";      // OK: person is a variable of type Person.
Person.firstName = "First";      // ERROR: Person is NOT an instance!
</pre>
</div>
<p>We can then access the different properties of the instance.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:12;" title="Objects.js">
jeremiah.firstName = "Jeremiah";
jeremiah.lastName = "van Oosten";
jeremiah.age = 35;
jeremiah.isMale = true;
</pre>
</div>
<p>We can delete a class by setting its reference to <strong>null</strong>.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:17;" title="Objects.js">
jeremiah = null;
</pre>
</div>
<p>If you try to access the properties of a deleted reference, you will get a <strong>NullReferenceException</strong> at run-time.</p>
<p>We can extend our class to contain functions.  A special function called a <strong>constructor</strong> can be defined using the name of the class:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="Objects.js">
class Person
{
    var firstName : String;
    var lastName : String;
    var age : int;
    var isMale : boolean;

    // Default constructor.
    function Person() {
    }        
}
</pre>
</div>
<p>We can also initialize the properties of our class if we supply a constructor that accepts arguments.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="Objects.js">
class Person
{
    var firstName : String;
    var lastName : String;
    var age : int;
    var isMale : boolean;

    // Parameterized constructor.
    function Person( firstName : String, lastName : String, age : int, isMale : boolean )
    {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.isMale = isMale;
    }
}

// Create an instance of a person using the parameterized constructor.
var jeremiah = new Person( "Jeremiah", "van Oosten", 35, true );
</pre>
</div>
<p>Within the scope of the class, we can use the <strong>this</strong> keyword to refer to the instance of the class.  In the previous example, we use the <strong>this</strong> keyword to differentiate between the class member variables and the constructor arguments.</p>
<p>We can also define member functions in the class.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="Objects.js">
class Person
{
	var firstName : String = "John";
	var lastName : String = "Doe";
	var age : int = 19;
	var isMale : boolean = true;
	
	function Person()
	{}
	
	function Person( firstName : String, lastName : String, age : int, isMale : boolean )
	{
		this.firstName = firstName;
		this.lastName = lastName;
		this.age = age;
		this.isMale = isMale;
	}

	function ToString() : String
	{
		var asText : String;
		
		asText =  "Name: " + firstName + " " + lastName + "\n";
		asText += "Age: " + age + "\n";
		asText += "Gender: " + (isMale ? "Male" : "Female");
		
		return asText;
	}
}
</pre>
</div>
<p>In the previous example, we declare a function called <strong>ToString()</strong> within the scope of the class.  This function also demonstrates a feature of functions that hasn&#8217;t been introduced yet: <strong>return values</strong> (return values are not unique to class functions).</p>
<p>A function can return a value to the caller using the <strong>return</strong> keyword. In this case, the <strong>ToString()</strong> function returns a value of type <strong>String</strong>.</p>
<span id="Rotation_Script"><h2>Rotation Script</h2></span>
<p>Now that we have a good understanding of functions, variables, types and classes, let&#8217;s put it to good use.  We will create a script that will rotate an object around the global Y-axis.  We will do this in 2 different ways which we will see changes the way the object behaves.</p>
<p>First, let&#8217;s create a new script. In your Unity project, create a new JavaScript asset called &#8220;<strong>RotateObject</strong>&#8220;.</p>
<p>Open the new script in <strong>MonoDevelop</strong> and copy-paste the following code into the script.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="RotateObject.js">
#pragma strict

var variableRotationRate = 0.0f;
var fixedRotationRate = 0.0f;

function Update () {
	transform.Rotate( Vector3.up * variableRotationRate );
}

function FixedUpdate() {
	transform.Rotate( Vector3.up * fixedRotationRate );
}
</pre>
</div>
<p>Now create a scene with 2 cubes.  Place the cubes close together (without overlapping) so you can see both of them in the scene view.  Name one cube &#8220;<strong>Cube01</strong>&#8221; and the other &#8220;<strong>Cube02</strong>&#8220;.</p>
<p>Make sure you aim the main camera at the cubes (hint: use the scene view to frame the cubes in the view then use the <strong>Align with View</strong> command (Ctrl+Shift+F) to align the main camera with the scene view).</p>
<p>Add a directional light as a child of the main camera GameObject to light the cubes. Zero the X, Y, Z position and rotation values of the directional light so it is always pointing in the direction of the camera.</p>
<p>Attach the <strong>RotateObject</strong> script component to each cube in the scene.</p>
<p>You should see something similar to what is shown below.</p>
<div id="attachment_3760" class="wp-caption alignnone" style="width: 993px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Rotate-Object-Scene.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Rotate-Object-Scene.png" alt="Unity - Rotate Object Scene" title="Unity - Rotate Object Scene" width="983" height="667" class="size-full wp-image-3760" /></a><p class="wp-caption-text">Unity &#8211; Rotate Object Scene</p></div>
<p>Select <strong>Cube01</strong> and set it&#8217;s <strong>Variable Rotation Rate</strong> value in the inspector to <strong>1</strong>.</p>
<p>Select <strong>Cube02</strong> and set it&#8217;s <strong>Fixed Rotation Rate</strong> value in the inspector to <strong>1</strong>.</p>
<p>Run the game. You should see something similar to what is shown below.</p>
<p><iframe src="http://3dgep.com/demos/ScriptingBasics/ScriptingBasics.html" scrolling="no" style="width:100%;min-height:380px"></iframe></p>
<p>You will notice that the two cubes are not synchronized despite the fact that we set both rotation rates to the same value of 1.  This is because one cube is performing its rotation in the <strong>Update()</strong> function and the other is performing its rotation in the <strong>FixedUpdate()</strong> function.  These two functions are being updated at different frequencies.</p>
<p>The frequency that the <strong>Update()</strong> function is invoked is also CPU bound. It will run faster on computers with faster CPUs and slower on computers with slower CPUs.  How can we ensure that the cubes rotate at the same rate regardless of the CPU speed?</p>
<p>To solve this, we must take time into consideration.</p>
<span id="Time"><h2>Time</h2></span>
<p>Unity provides a class object called <strong>Time</strong> that we can use to solve our frame-rate issues.  The <strong>Time</strong> class provides a <strong>static</strong> member variable called <strong>deltaTime</strong> that we can use to adjust our rotation rate.</p>
<div class="my-note">
You can declare a variable as <strong>static</strong> by using the <strong>static</strong> keyword.  You do not need an instance of a class to access static variables.
</div>
<p>Let&#8217;s adjust the script to take time into consideration.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="RotateObject.js">
#pragma strict

var variableRotationRate = 0.0f;
var fixedRotationRate = 0.0f;

function Update () {
	transform.Rotate( Vector3.up * Time.deltaTime * ( variableRotationRate * 360.0f ) );
}

function FixedUpdate() {
	transform.Rotate( Vector3.up * Time.deltaTime * ( fixedRotationRate * 360.0f ) );
}
</pre>
</div>
<p>If you copy paste this code to the <strong>RotateObject.js</strong> script asset and run the game again, you may notice that the cubes are rotating really fast.  I multiplied the rotation rate by 360 to make the cubes rotate at <strong>RotationRate</strong> rotations per second.  Previously, we set the rotation rate to 1 for both variable and fixed rotation rates which will cause the cubes to rotate one full rotation every second.</p>
<p>Select <strong>Cube01</strong> and set its <strong>Variable Rotation Rate</strong> to <strong>0.25</strong> and its <strong>Fixed Rotation Rate</strong> to <strong>0</strong>. </p>
<p>Select <strong>Cube02</strong> and set its <strong>Variable Rotation Rate</strong> to <strong>0</strong> and its <strong>Fixed Rotation Rate</strong> to <strong>0.25</strong>.</p>
<p>Now the cubes should rotate at a rate of 90 degrees per second.  It should take exactly 4 seconds to make a full rotation.</p>
<p>Now run the game again and you will notice that the two cubes rotate at the same speed!</p>
<p><iframe src="http://3dgep.com/demos/ScriptingBasics/ScriptingBasics2.html" scrolling="no" style="width:100%;min-height:380px"></iframe></p>
<p>There will be many situations where using the <strong>Time.deltaTime</strong> value will be useful.</p>
<span id="Conditional_Logic"><h2>Conditional Logic</h2></span>
<p>We now have a better understand of types and variables in JavaScript but there is one more extremely important concept we must understand before we can make interesting gameplay.  Without conditional logic, we couldn&#8217;t make any choices in our gameplay.  We couldn&#8217;t tell our player to jump, or shoot, or taunt the other players.</p>
<p>In order to use conditional logic correctly, we must first understand some basics about logic.  We will now put the <strong>boolean</strong> type introduced earlier to good use.</p>
<span id="Boolean_Logic"><h3>Boolean Logic</h3></span>
<p>The most basic concept of boolean logic is the concept of &#8220;<strong>true</strong>&#8221; and &#8220;<strong>false</strong>&#8220;.  We have a <strong>boolean</strong> data type that can be used to store these values. </p>
<p>We can compare values to test if a certain condition is <strong>true</strong> or <strong>false</strong>. </p>
<p>The table below shows the different comparison operators that are available.</p>
<table width="100%" border="0">
<tr>
<th style="text-align: center;">Operator</th>
<th style="text-align: center;">Operation</th>
<th style="text-align: center;">Desctiption</th>
</tr>
<tr>
<td>==</td>
<td nowrap="nowrap">Equality</td>
<td>The <strong>equality </strong>operator is used to test if two values are the same.</td>
</tr>
<tr>
<td>!=</td>
<td nowrap="nowrap">Inequality</td>
<td>The <strong>inequality </strong>operator is used to test if two values are not the same.</td>
</tr>
<tr>
<td>&gt;</td>
<td nowrap="nowrap">Greater than</td>
<td>The <strong>greater than </strong>operator is used to test if the value on the left of the operator is greater than the value on the right.</td>
</tr>
<tr>
<td>&lt;</td>
<td nowrap="nowrap">Less than</td>
<td>The <strong>less than </strong>opertator is used to test if the value on the left of the operator is less than the value on the right.</td>
</tr>
<tr>
<td>&gt;=</td>
<td nowrap="nowrap">Greater than or equal to</td>
<td>The <strong>greater than or equal</strong> operator is used to test if the value on the left of the operator is greater than or the same as the value on the right.</td>
</tr>
<tr>
<td>&lt;=</td>
<td nowrap="nowrap">Less than or equal to</td>
<td>The <strong>less than or equal</strong> operator is used to test if the value on the left of the operator is less than or the same as the value on the right.</td>
</tr>
</table>
<p>We can use these comparison operators together with the following logical operators to form complex logical conditions.</p>
<table width="100%" border="0">
<tr>
<th style="text-align: center;">Operator</th>
<th style="text-align: center;" nowrap="nowrap">Operation</th>
<th style="text-align: center;">Description</th>
</tr>
<tr>
<td>&amp;&amp;</td>
<td nowrap="nowrap"><strong>And </strong>operator.</td>
<td>Returns <strong>true </strong>if both left and right operands are true.</td>
</tr>
<tr>
<td>||</td>
<td nowrap="nowrap"><strong>Or </strong>operator.</td>
<td>Returns <strong>true </strong>if either the left or the right operands are true.</td>
</tr>
<tr>
<td>!</td>
<td nowrap="nowrap"><strong>Not </strong>operator.</td>
<td><strong>Reverses </strong>the value of the boolean expression (makes true false and false true).</td>
</tr>
</table>
<p>The first type of conditional we will look at is the <strong>if</strong> statement.</p>
<span id="If_Statement"><h4>If Statement</h4></span>
<p>The <strong>If</strong> statement has the following syntax.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
if ( condition )
{
    // Statements to execute if condition is true.
}
</pre>
</div>
<p>The following statements will all evaluate to <strong>true</strong>:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var a = 3;
var b = 5;
var c = 10;

var strHello = "Hello";
var strWorld = "World!";

var strHelloAgain = strHello;

if ( a &lt; b ) // TRUE: 3 is LESS THAN 5
{}

if ( b &lt; c ) // TRUE: 5 is LESS THAN 10
{}

if ( a &lt; b &amp;&amp; b &lt; c ) // TRUE: 3 is LESS THAN 5 AND 5 is LESS THAN 10
{}

if ( c &gt; a || a &gt; c ) // TRUE: 10 is GREATER THAN 3 OR 3 is GREATER THAN 10
{}

if ( strHello != strWorld ) // TRUE: "Hello" is NOT EQUAL "World!"
{}

if ( strHello == strHelloAgain ) // TRUE: "Hello" is EQUAL to "Hello"
{}
</pre>
</div>
<p>The following statements all evaluate to <strong>false</strong>:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
if ( a &gt; b ) // FALSE: 3 is NOT GREATER THAN 5
{}

if ( b &gt; c ) // FALSE: 5 is NOT GREATER THAN 10
{}

if ( a &lt; b &amp;&amp; b &gt; c ) // FALSE: 3 is LESS THAN 5 but 5 is NOT GREATER THAN 10
{}

if ( a &gt; b || b &gt; c ) // FALSE: 3 is NOT GREATER THAN 5 and 5 is NOT GREATER THAN 10

if ( strHello == strWorld ) // FALSE: "Hello" is NOT EQUAL to "World!"
{}
</pre>
</div>
<p>Optionally, we can execute some other statements only if the <strong>if</strong> condition fails.  This is called an <strong>if-then-else</strong> statement.</p>
<span id="If-Then-Else"><h4>If-Then-Else</h4></span>
<p>The if-then-else statement has the following syntax.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
if ( condition )
{
    // Execute these statements if the condition is true.
}
else
{
    // Execute these statements if the condition is false.
}
</pre>
</div>
<p>We can also nest <strong>if-then-else</strong> statements.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
if ( condition1 )
{
    // Execute these statements if condition1 is true.
}
else if ( condition2 )
{
    // Execute these statements if condition2 is true.
}
else
{
    // Execute these statements if neither condition1 or condition2 are true.
}
</pre>
</div>
<p>If you you find you have to write a lot of nested <strong>if-then-else</strong> statements, you may want to consider using a <strong>switch</strong> statement.</p>
<span id="Switch_Statement"><h4>Switch Statement</h4></span>
<p>The <strong>switch</strong> statement has the following syntax.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
switch ( &lt;expression&gt; )
{
case &lt;test1&gt;:
    // Statements to execute if expression evaluates to test1.
    break; // Break-out of switch statement.
case &lt;test2&gt;:
    // Statements to execute if expression evaluates to test2.
    break; // Break-out of switch statement.
case &lt;test3&gt;:
    // Statements to execute if expression evaluates to test3.
    break;
default:
    // Statements to execute if no test passes.
}
</pre>
</div>
<p><strong>Switch</strong> statements are very common way of implementing state-machines.  Let&#8217;s look at a real-world example.</p>
<p>Suppose we have a character controller that can have the following states:</p>
<ul>
<li><strong>Idle</strong>: The character is not moving. Perform some &#8220;Idle&#8221; animation.</li>
<li><strong>Walk</strong>: The character is walking. Perform the &#8220;Walk&#8221; animation.</li>
<li><strong>Run</strong>: The character is running. Perform the &#8220;Run&#8221; animation.</li>
<li><strong>Jump</strong>: The character is jumping. Perform the &#8220;Jump&#8221; animation.</li>
<li><strong>Fire</strong>: The character is firing a weapon. Perform the &#8220;Fire&#8221; animation.</li>
</ul>
<p>We could implement this state machine using the following <strong>switch</strong> statement.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
#pragma strict

enum State
{
	Idle,
	Walk,
	Run,
	Jump,
	Fire
}

private var currentState : State = State.Idle;

function Update () 
{
	switch ( currentState )
	{
	case State.Idle:
		DoIdle();
		break;
	case State.Walk:
		DoWalk();
		break;
	case State.Run:
		DoRun();
		break;
	case State.Jump:
		DoJump();
		break;
	case State.Fire:
		DoFire();
		break;
	default:
		currentState = State.Idle;
	}
}
</pre>
</div>
<p>In this code example, we use an <strong>enumeration</strong> to define some valid states the character can have.  We must also define a variable which will store the character&#8217;s current state.  This variable is marked &#8220;<strong>private</strong>&#8221; which means that this variable will neither be available in the <strong>Inspector</strong> nor will it be accessible by other scripts attached to the <strong>GameObject</strong>.</p>
<p>If the character is in the <strong>Idle</strong> state, we execute the <strong>DoIdle()</strong> function.</p>
<p>If the character is in the <strong>Walk</strong> state, we execute the <strong>DoWalk()</strong> function.</p>
<p>If the character is in the <strong>Run</strong> state, we execute the <strong>DoRun()</strong> function.</p>
<p>If the character is in the <strong>Jump</strong> state, we execute the <strong>DoJump()</strong> function.</p>
<p>If the character is in the <strong>Fire</strong> state, we execute the <strong>DoFire()</strong> function.</p>
<p>If the character is in some invalid state, then we set the current state to a valid state and do nothing until the next time <strong>Update()</strong> is invoked on this script.</p>
<span id="While_Loops"><h4>While Loops</h4></span>
<p>There might be a situation where you need to execute a block of code as long as some condition is true.  In this case, we can use a <strong>while loop</strong>.</p>
<p>The syntax for the while loop is:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
while ( condition )
{
    // Do something as long as condition is true.
}
</pre>
</div>
<p>For example, the following example shows how we can spawn 15 enemies.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var numEnemies = 15;

var i = 0;
while ( i < numEnemies )
{
    SpawnEnemy();
    ++i;
}
</pre>
</div>
<span id="Do-While_Loops"><h4>Do-While Loops</h4></span>
<p>In some cases, you may want to make that a block of code gets executed at least once before the while condition is tested.  For this, we can use the <strong>do-while loop</strong>.</p>
<p>The <strong>do-while loop</strong> has the following syntax.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" >
do
{
    // Do something before we test the while condition.
} while ( condition ); // Keep doing it as long as condition is true.
</pre>
</div>
<span id="For_Loops"><h4>For Loops</h4></span>
<p>The <strong>for loop</strong> is useful when you want to iterate arrays or other types of enumerable containers or you want to execute a statement block a certain number of times.</p>
<p>The syntax of the <strong>for loop</strong> is:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="Script.js">
for ( &lt;initializer&gt;; &lt;condition&gt;; &lt;iterator&gt; )
{
    // Operate on element.
}
</pre>
</div>
<p>We can convert the enemy spawn example to use a <strong>for loop</strong> instead of a <strong>while loop</strong>.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var numEnemies = 15;

for ( var i = 0; i < numEnemies; ++i )
{
    SpawnEnemy();
}
</pre>
</div>
<span id="For-In_Loop"><h4>For-In Loop</h4></span>
<p>Iterating (looping over the elements of) arrays is so common in programming that there is a special construct in JavaScript that allows you to loop over the elements of a container. For this purpose, we can use the <strong>for-in</strong> loop.</p>
<p>The syntax of the for-in loop is:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
for ( element in container )
{
    // Operate on element.
}
</pre>
</div>
<p>For example, we can iterate arrays using the following code:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;">
var stringArray = new String[5];

stringArray[0] = "Hello, ";
stringArray[1] = "my ";
stringArray[2] = "name ";
stringArray[3] = "is ";
stringArray[4] = "Jeremiah ";

for ( val in stringArray )
{
	Debug.Log( val );
}
</pre>
</div>
<p>This will output the following code in the debug console:</p>
<pre>
Hello, 
my 
name
is 
Jeremiah
</pre>
<div class="my-note">
Only containers that implement the <strong>System.Collections.IEnumerable</strong> interface can be enumerated using the <strong>for-in</strong> loop. Both JavaScript arrays and built-in arrays implement the <strong>IEnumerable</strong> interface.
</div>
<p>So I think that's enough blah-blah-blah.  Let's put all this knowledge to good use and make a simple prototype of a wall breaking game.</p>
<span id="Wall_Breaker"><h1>Wall Breaker</h1></span>
<p>In this tutorial you will put all of the knowledge you just learned to good use.  We are going to make a simple demo called "Wall Breaker".</p>
<p>First, we going to create a wall of bricks (cubes). The width and height of our brick-wall should be tweakable.</p>
<p>Then we want to be able to shoot a ball at our wall and see how it collapses.  We should be able to tweak the initial velocity of the ball.</p>
<span id="Create_A_New_Scene"><h2>Create A New Scene</h2></span>
<p>Open your test project in Unity (or create a new project) and create a new scene.</p>
<div id="attachment_3809" class="wp-caption alignnone" style="width: 1034px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-1.gif"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-1.gif" alt="Unity - Wall Breaker - New Scene" title="Unity - Wall Breaker - New Scene" width="1024" height="638" class="size-full wp-image-3809" /></a><p class="wp-caption-text">Unity - Wall Breaker - New Scene</p></div>
<p>Save your scene. I suggest you call your scene file "<strong>WallBreaker</strong>" and you save it in a folder called "<strong>Scenes</strong>".</p>
<span id="Create_A_Plane"><h2>Create A Plane</h2></span>
<p>Create a new <strong>Plane GameObject</strong> in your scene (select <strong>GameObject -> Create Other -> Plane</strong> from the main menu).</p>
<div id="attachment_3812" class="wp-caption alignnone" style="width: 1034px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-2.gif"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-2.gif" alt="Unity - Wall Breaker (2)" title="Unity - Wall Breaker (2)" width="1024" height="638" class="size-full wp-image-3812" /></a><p class="wp-caption-text">Unity - Wall Breaker (2)</p></div>
<p>Set the <strong>Position</strong> and <strong>Rotation</strong> of the <strong>Plane GameObject</strong> to <strong>0</strong> in all axes.</p>
<p><strong>Scale</strong> the Plane to <strong>10</strong> units in the <strong>X</strong> axis and <strong>10</strong> units in the <strong>Z</strong> axis.  Make sure the <strong>Scale</strong> in the <strong>Y</strong> axis is <strong>1</strong>.</p>
<div id="attachment_3810" class="wp-caption alignnone" style="width: 1034px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-3.gif"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-3.gif" alt="Unity - Wall Breaker (3)" title="Unity - Wall Breaker (3)" width="1024" height="638" class="size-full wp-image-3810" /></a><p class="wp-caption-text">Unity - Wall Breaker (3)</p></div>
<p>Save your scene!</p>
<span id="Create_a_Brick"><h2>Create a Brick</h2></span>
<p>Create a new <strong>Cube GameObject</strong> in your scene (select <strong>GameObject -> Create Other -> Cube</strong> from the main menu).</p>
<p><strong>Scale</strong> the <strong>Cube</strong> so that it is more "brick shaped".  Set the <strong>Scale</strong> in the <strong>Y</strong> and <strong>Z</strong> axes to <strong>0.5</strong>.</p>
<div id="attachment_3816" class="wp-caption alignnone" style="width: 1034px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-5.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-5.png" alt="Unity - Wall Breaker (4)" title="Unity - Wall Breaker (4)" width="1024" height="638" class="size-full wp-image-3816" /></a><p class="wp-caption-text">Unity - Wall Breaker (4)</p></div>
<p>If the <strong>Cube</strong> was placed at the origin (position is at 0, 0, 0) then the <strong>Cube GameObject</strong> will be sitting inside the plane.  Use the transform gizmo to move the cube just above the plane.  We've scaled the <strong>Cube</strong> to <strong>0.5</strong> units in the <strong>Y</strong> axis so if we translate the <strong>Cube</strong> to <strong>0.25</strong> units in the <strong>Y</strong> axes then the <strong>Cube</strong> will be sitting directly on the <strong>Plane</strong>.</p>
<div id="attachment_3827" class="wp-caption alignnone" style="width: 920px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-5-2.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-5-2.png" alt="Unity - Wall Breaker (5)" title="Unity - Wall Breaker (5)" width="910" height="630" class="size-full wp-image-3827" /></a><p class="wp-caption-text">Unity - Wall Breaker (5)</p></div>
<p>We want our <strong>Cube</strong> to be Physics controlled so we must add a <strong>Rigidbody</strong> component to the cube.  Select the <strong>Cube GameObject</strong> in the <strong>Hierarchy</strong> view and select <strong>Component -> Physics -> Rigidbody</strong> from the main menu.</p>
<div id="attachment_3818" class="wp-caption alignnone" style="width: 1034px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-6.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-6.png" alt="Unity - Wall Breaker (6)" title="Unity - Wall Breaker (6)" width="1024" height="638" class="size-full wp-image-3818" /></a><p class="wp-caption-text">Unity - Wall Breaker (6)</p></div>
<p>Save the scene!</p>
<span id="Create_a_Canon_Ball_Prefab"><h2>Create a Canon Ball Prefab</h2></span>
<p>We will also create a canon ball that will be used shoot at our brick wall.</p>
<p>Create a new <strong>Sphere GameObject</strong> (select GameObject -> Create Other -> Sphere).  The position of the sphere is irrelevant because it will only be used to create a <strong>Prefab</strong>.</p>
<p>We also want the <strong>Sphere</strong> to be physics controlled so let's add a <strong>Rigidbody</strong> component to the <strong>Sphere GameObject</strong>. Select the <strong>Sphere GameObject</strong> in the <strong>Hierarchy</strong> view and select <strong>Component -> Physics -> Rigidbody</strong> from the main menu.</p>
<div id="attachment_3829" class="wp-caption alignnone" style="width: 920px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-7.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-7.png" alt="Unity - Wall Breaker (7)" title="Unity - Wall Breaker (7)" width="910" height="630" class="size-full wp-image-3829" /></a><p class="wp-caption-text">Unity - Wall Breaker (7)</p></div>
<p>Create a folder in your <strong>Project</strong> view called <strong>Prefabs</strong>.</p>
<p>Now drag-and-drop the <strong>Sphere GameObject</strong> from the <strong>Hierarchy</strong> view into the <strong>Prefabs</strong> folder in the <strong>Project</strong> view.  We now have a <strong>GameObject</strong> template (<strong>Prefab</strong>) that we can instantiate at run-time.</p>
<p>Delete the original <strong>Sphere</strong> <strong>GameObject</strong> from the scene.</p>
<p>We should have something similar to what is shown below.</p>
<div id="attachment_3831" class="wp-caption alignnone" style="width: 920px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-8.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-8.png" alt="Unity - Wall Breaker (8)" title="Unity - Wall Breaker (8)" width="910" height="630" class="size-full wp-image-3831" /></a><p class="wp-caption-text">Unity - Wall Breaker (8)</p></div>
<p>Save your scene!</p>
<span id="Adding_the_Logic"><h2>Adding the Logic</h2></span>
<p>Create a new <strong>JavaScript</strong> asset in your <strong>Scripts</strong> folder called "<strong>WallBreaker</strong>".  Open the new <strong>WallBreaker</strong> <strong>JavaScript</strong> file in <strong>MonoDevelop</strong>.</p>
<p>Initially, your script will contain the default JavaScript template.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="Script.js">
#pragma strict

function Start () {

}

function Update () {

}
</pre>
</div>
<p>First, we need to define a few parameters that will be exposed in the <strong>Inspector</strong> view.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:8;" title="WallBreaker.js">
var brickPrefab : GameObject;
var ballPrefab : GameObject;
</pre>
</div>
<p>At the top of the source file, we declare two variables that will be used to store references to <strong>Prefabs</strong> that we will instantiate while the game is running.  Initially, these variables are empty (<strong>null</strong>) and we cannot use empty variables.  These variables will be set in the <strong>Inspector</strong> view.</p>
<p>Next, we also want to specify how many bricks will be used to build our wall. </p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:11;" title="WallBreaker.js">
var numBricksX : int = 5;
var numBricksY : int = 5;
</pre>
</div>
<p>For this, we will use <strong>numBricksX</strong> to specify how many bricks to place in the <strong>X</strong> axis (to the right of our original brick) and <strong>numBricksY</strong> is used to specify how many bricks to place in the <strong>Y</strong> axis (above the original brick).  The default value of 5 for each of these variables will produce a wall that is 5x5 = 25 bricks.  25 bricks is not a very big wall but we will tweak these values in the <strong>Inspector</strong> later.</p>
<p>We also want to specify how much force will be applied to our canon ball when we shoot it at the brick wall.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:14;" title="WallBreaker.js">
// How much force to put on the ball.
var forceMultiplier : float = 100;
</pre>
</div>
<p>This may not be enough force to shoot our canon ball, but again we will be able to tweak this value in the <strong>Inspector</strong> later.</p>
<p>We will be able to shoot canon balls into the scene by clicking on the game window with the mouse.  Each time we click, a new canon ball will be instantiated.  If the user keeps clicking with the mouse, we will have more and more balls in our scene. At some point the Physics engine will start to get very very slow trying to update 2000 spheres in our scene.  To prevent the player from adding an infinite number of canon balls in the scene, we will keep track of each new canon ball in an array and if there are more than 10 canon balls in the scene, we will remove the oldest one.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:16;" title="WallBreaker.js">
private var balls = new Array();
</pre>
</div>
<p>The <strong>balls</strong> array will be used to store references to all of the cannon balls that have been shot into the scene.  Once our array gets to a certain size, we will remove the oldest ball in the list.</p>
<p>Since we want to make sure that the mouse cursor is always visible on screen, we will set the <strong>showCursor</strong> property of the <strong>Screen</strong> class to <strong>true</strong>.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:18;" title="WallBreaker.js">
function Awake()
{
	Screen.showCursor = true;
}
</pre>
</div>
<p>We will use the <strong>Start()</strong> function to build up our wall.</p>
<span id="The_Start_Function"><h3>The Start Function</h3></span>
<p>The Start function is executed after all of the <strong>GameObjects</strong> in the scene have been created.  This is where we will use the <strong>brick prefab</strong> to build our brick wall.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:23;" title="WallBreaker.js">
function Start () 
{
	if ( brickPrefab != null )
	{
		var brickSize = brickPrefab.renderer.bounds.size;
				
		var X = brickPrefab.transform.position.x + brickSize.x;
		var Y = brickPrefab.transform.position.y;
		var Z = brickPrefab.transform.position.z;
		
		var brickOrientation = brickPrefab.transform.rotation;
		
		for( var i = 0; i &lt; numBricksY; ++i )
		{
			for ( var j = 0; j &lt; numBricksX; ++j )
			{
				if ( i == 0 &amp;&amp; j == ( numBricksX - 1 ) ) break;
				Instantiate( brickPrefab, Vector3( X, Y, Z ), brickOrientation );
				X += brickSize.x;
			}
			X = brickPrefab.transform.position.x;
			Y += brickSize.y;
		}
	}
}
</pre>
</div>
<p>The first thing we do in this function is check to make sure our brick prefab is not <strong>null</strong>. There must be a valid reference to a <strong>GameObject</strong> before we can do anything with it.  We will set a reference to the brick GameObject that exists in our scene using the Inspector later.</p>
<p> If we have a valid reference to a <strong>GameObject</strong>, we will query the size (dimensions) of the <strong>GameObject</strong> using the <strong>GameObject</strong>'s <strong>Renderer</strong> component.  The <strong>GameObject</strong>'s <strong>Renderer</strong> component can be accessed using the <strong>renderer</strong> property of the <strong>GameObject</strong>.</p>
<p>Every type that derives from the <strong>Component</strong> type (including the <strong>GameObject</strong> type and <strong>MonoBehaviour</strong> type) have several predefined properties to access the more common component types.  I suggest you familiarize yourself with the <a href="http://docs.unity3d.com/Documentation/ScriptReference/Component.html" title="Component" target="_blank">Component</a> class, the <a href="http://docs.unity3d.com/Documentation/ScriptReference/GameObject.html" title="GameObject" target="_blank">GameObject</a> class and the <a href="http://docs.unity3d.com/Documentation/ScriptReference/MonoBehaviour.html" title="MonoBehaviour" target="_blank">MonoBehaviour</a> class.</p>
<p>On lines 29-31, we use the brick prefab's position in the scene to determine the initial position of our brick wall.  On line 29 We add the size of the brick in the X axis so that we don't create the first brick inside the brick that is already in our scene.</p>
<p>On line 33, we store the orientation of the original brick. We will use this orientation to rotate the new bricks in the scene to match the orientation of the original brick.</p>
<p>To build our brick wall we will create several <strong>rows</strong> of bricks.  The <strong>width</strong> of each <strong>row</strong> of bricks is determined by the <strong>numBricksX</strong> variable.  The number of rows, or the height of the brick wall is determined by the <strong>numBricksY</strong> variable.  For example, if <strong>numBricksX</strong> is <strong>5</strong> and <strong>numBricksY</strong> is <strong>5</strong>, we will create <strong>5 rows</strong> of <strong>5</strong> bricks for a total of <strong>25 bricks</strong>.</p>
<p>The outer <strong>for-loop</strong> (on line 35) will loop through the rows of bricks.  The inner <strong>for-loop</strong> (on line 37) will create a brick for each column of the brick wall.</p>
<p>On line 39 we check to see if we are at the end of the first row of bricks.  If we are, we want to place 1 less brick to compensate for the original brick that is in the scene.  If we didn't account for this extra brick, we'd have one extra brick on the first row of bricks (which would just look silly).</p>
<p>The <strong>break</strong> keyword will break-out of the currently executing for-loop.  In this case, we are in the inner for-loop so the <strong>break</strong> keyword will break-out of the inner for-loop and the script will continue executing the outer for-loop.</p>
<p>On line 40, we use the <strong>Instantiate</strong> function to create a copy of our brick prefab.  The first argument must be a valid reference to the <strong>GameObject</strong> we want to duplicate. The second argument to the <strong>Instantiate</strong> function is the position in world-space where we want the cloned object to be placed. And the third and final argument to the <strong>Instantiate</strong> function is the <strong>rotation</strong> of the cloned object.  The <strong>Instantiate</strong> function will return a reference to the cloned object.  If we don't plan on doing anything with the cloned object, we can simply ignore the returned reference.</p>
<p>On line 41, we update the <strong>X</strong> variable to the position where the next brick will be cloned.</p>
<p>Once we've created a row of bricks, we move up the <strong>Y</strong> axis to create another row of bricks.</p>
<p>And that's all there is to creating a grid of bricks.</p>
<div class="my-note">
<strong>TRY THIS</strong>: Insert the following line of code inside the inner for-loop (just after line 41) and run your game:</p>
<pre>
yield WaitForSeconds( 0.1 );
</pre>
<p>If done correctly, you will be able to see the bricks "popping" into existence as they are being instantiated.  This will allow you to visualize how the for-loops are working to create the brick wall.
</p></div>
<p>Now let's handle the canon ball firing.</p>
<span id="The_Update_Function"><h3>The Update Function</h3></span>
<p>In the <strong>Update()</strong> function, we will handle the firing of the canon ball.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:49;" title="WallBreaker.js">
function Update () 
{
	if ( Input.anyKeyDown &amp;&amp; ballPrefab != null )
	{
		var ray : Ray = Camera.main.ScreenPointToRay( Input.mousePosition );
		var ball = Instantiate( ballPrefab, ray.origin, Quaternion.identity );
		// Put a force on the ball in the direction of the ray generated by the position of the mouse.
		ball.rigidbody.AddForce( ray.direction * forceMultiplier );
		balls.Push( ball );
	}
	
	if ( balls.length &gt; 10 )
	{
		var removeMe : Object = balls[0];
		balls.RemoveAt(0);
		Destroy(removeMe);
	}
}
</pre>
</div>
<p>Anytime the player presses a key on the keyboard or presses a button on the mouse, we will fire a ball into the scene.  Of course, we also want to make sure that the <strong>ballPrefab</strong> has a valid reference to a <strong>prefab</strong> object.</p>
<p>If we have a valid reference to a prefab, we want to determine where the mouse cursor is in world-space.  In order to determine the world-space position of the mouse cursor, we need to have a camera to project through.  The <strong>Camera</strong> class has a reference to the main camera in the scene.  Our simple scene only defines one camera and by default, this camera is the main camera.  </p>
<p>The <strong>Camera</strong> class defines several functions to transform from screen-space (where our mouse cursor is) into world-space (where our bricks are) as well as transforming world-space positions back to screen-space (useful for adding 2D GUI elements to objects in 3D space).  In this case, we use the <strong>Camera's</strong> <strong>ScreenPointToRay</strong> function to convert our mouse cursor position in screen-space into a 3D <strong>ray</strong> in world-space.  The <strong>ray's</strong> <strong>origin</strong> will be the position of the camera (the eye position) and the <strong>direction</strong> of the <strong>ray</strong> will point from the camera's position through the screen at the  position of the mouse cursor.</p>
<p>We can use the <strong>ray</strong> variable returned from the <strong>ScreenPointToRay()</strong> function for 2 things:</p>
<ul>
<li>Use the <strong>Ray.origin</strong> property to determine the position to instantiate our canon ball.</li>
<li>Use the <strong>Ray.direction</strong> property to determine the direction to fire our canon ball.</li>
</ul>
<p>On line 54 we use the <strong>Instantiate</strong> function again but this time to create a canon ball sphere object.  In this case, we <strong>ray.origin</strong> to position the new sphere instance and the <strong>Quaternion.identity</strong> property to determine the rotation of the new sphere.</p>
<div class="my-note">
A <strong>Quaternion</strong> class is used to represent an orientation (rotation) in 3D space and the <strong>Quaternion.identity</strong> property represents a zero rotation (no rotation in any axis).
</div>
<p>The next thing we need to do is to propel our canon ball forward in the direction we clicked on the screen.  We do this by applying a force on the <strong>Rigidbody</strong> component of the new ball instance.  Without a valid <strong>Rigidbody</strong> component on the ball prefab, we could not apply physical forces to the ball instance.</p>
<p>We use the <strong>ray.direction</strong> vector to determine the direction to fire the ball.  The <strong>ray.direction</strong> property is a normalized (length of 1) vector that we can scale by multiplying by the <strong>forceMultiplier</strong> variable.  The value of the <strong>forceMultiplier</strong> will determine how fast our ball is projected into the scene.</p>
<p>We also want to make sure the player cannot add an infinite number of balls in the scene.  So we add the ball to the <strong>balls</strong> array using the <strong>Push()</strong> function on the array.  This will add a reference of the ball instance to the last element of the array.  If the ball array gets too long (more than 10 elements in this case), then we will remove instances starting from the first element.  The <strong>RemoveAt()</strong> function will remove an element from the array at a particular index.  All elements in the array that have an index greater than the index specified in this function will be shifted to fill the gap.  By removing the element at index 0, we know we are always removing the oldest ball first.</p>
<p><strong>GameObjects</strong> can be removed from the scene using the <strong>Destroy()</strong> method.</p>
<span id="Adding_the_Logic_to_the_Scene"><h2>Adding the Logic to the Scene</h2></span>
<p>If you run the game now nothing will happen.  We haven't added the script we just created to the scene yet.</p>
<p>Create an empty <strong>GameObject</strong> in the scene.  Rename the empty <strong>GameObject</strong> to "<strong>Logic Controller</strong>" or something similar.</p>
<p>Drag-and-drop the <strong>WallBreaker</strong> script asset from the <strong>Project</strong> view onto the <strong>Logic Controller</strong> GameObject in the <strong>Hierarchy</strong> view.</p>
<div id="attachment_3843" class="wp-caption alignnone" style="width: 970px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-9.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-9.png" alt="Unity - Wall Breaker (9)" title="Unity - Wall Breaker (9)" width="960" height="656" class="size-full wp-image-3843" /></a><p class="wp-caption-text">Unity - Wall Breaker (9)</p></div>
<p>Before we can play the game, we need to assign the <strong>Brick Prefab</strong> and the <strong>Ball Prefab</strong> references to our <strong>Wall Breaker</strong> script component.</p>
<p>Drag the <strong>Cube GameObject</strong> (the original brick) from the <strong>Hierarchy</strong> view onto the <strong>Brick Prefab</strong> variable in the <strong>Wall Breaker</strong> script component attached to the <strong>Logic Controller</strong> <strong>GameObject</strong>.</p>
<p>Drag the <strong>Sphere prefab</strong> from the <strong>Project</strong> view onto the <strong>Ball Prefab</strong> variable in the <strong>Wall Breaker</strong> script component attached to the <strong>Logic Controller</strong> <strong>GameObject</strong>.</p>
<div id="attachment_3844" class="wp-caption alignnone" style="width: 970px"><a href="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-10.png"><img src="http://3dgep.com/wp-content/uploads/2012/09/Unity-Wall-Breaker-10.png" alt="Unity - Wall Breaker (10)" title="Unity - Wall Breaker (10)" width="960" height="656" class="size-full wp-image-3844" /></a><p class="wp-caption-text">Unity - Wall Breaker (10)</p></div>
<p>Save your scene!</p>
<p>If you play the game now, you probably won't see very much because we haven't added any lights to the scene yet.</p>
<p>Add a directional light to the <strong>Main Camera</strong> and zero the position and rotation so that the directional light is always pointing in the direction of the camera.</p>
<span id="Tweaking_and_Polish"><h2>Tweaking and Polish</h2></span>
<p>Now that we have the main functionality of our game working, we can tweak a few of the variables and add some polish.</p>
<ul>
<li>Make the wall 15 bricks wide and 15 bricks high.</li>
<li>Adjust the force multiplier to fire the balls faster.  I found that 1300 was a good force to shoot the ball.</li>
<li>Add spotlight that is looking down on your wall.  Make the spotlight cone large enough to brighten the wall.</li>
<li>Add a texture to the original brick in the scene.</li>
<li>Add a texture to the ball prefab in the project view.</li>
<li>Position and orient the <strong>Main Camera</strong> so that your entire wall is in view when you play the game.</li>
<li>Apply any other tweak values or polish to your game to make it more fun.</li>
</ul>
<span id="Playing_your_Game"><h2>Playing your Game</h2></span>
<p>When you are finished, your final game should look something similar to what is shown below.</p>
<p><iframe src="http://3dgep.com/demos/ScriptingBasics/WallBreaker.html" scrolling="no" style="width:100%;min-height:380px"></iframe></p>
<p>Click with your mouse in the window to fire a ball at the wall.</p>
<span id="Conclusion"><h1>Conclusion</h1></span>
<p>This article covers a lot of details.  I introduced some basic JavaScript principles such as functions, variables, class objects, and logical operations. I also introduced instantiating prefabs from both a scene object and a prefab asset in the <strong>Project</strong> view using the <strong>Instantiate()</strong> function.  We also learned how to use Arrays to store lists of objects. And you also learned how to keep your game running smoothly by destroying the excessive GameObjects using the <strong>Destroy()</strong> function.</p>
<p>I hope that you have learned enough to get you started scripting in Unity and you also learned how easy it is to add functionality to your game.</p>
<p>From here, I recommend you try to create your own interesting prototypes that may someday become the next block-buster game title!</p>
<span id="References"><h1>References</h1></span>
<p>The Unity Scripting Reference: <a href="http://docs.unity3d.com/Documentation/ScriptReference/index.html" title="http://docs.unity3d.com/Documentation/ScriptReference/index.html" target="_blank">http://docs.unity3d.com/Documentation/ScriptReference/index.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://3dgep.com/?feed=rss2&#038;p=3474</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Unity Asset Pipeline, GameObjects and Components</title>
		<link>http://3dgep.com/?p=3477</link>
		<comments>http://3dgep.com/?p=3477#comments</comments>
		<pubDate>Tue, 14 Aug 2012 10:57:46 +0000</pubDate>
		<dc:creator>Jeremiah van Oosten</dc:creator>
				<category><![CDATA[Unity]]></category>
		<category><![CDATA[assets]]></category>
		<category><![CDATA[components]]></category>
		<category><![CDATA[GameObject]]></category>
		<category><![CDATA[Mesh]]></category>
		<category><![CDATA[model]]></category>
		<category><![CDATA[physics]]></category>
		<category><![CDATA[rendering]]></category>
		<category><![CDATA[Scripts]]></category>

		<guid isPermaLink="false">http://3dgep.com/?p=3477</guid>
		<description><![CDATA[In this article, I want to introduce some basic Unity concepts such as the Asset pipeline and the GameObject-Component model and introduce a few of the Components that Unity provides. <a href="http://3dgep.com/?p=3477">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<div id="attachment_3699" class="wp-caption alignleft" style="width: 160px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Logo-2-512x512.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Logo-2-512x512-150x150.png" alt="Unity - Assets" title="Unity - Assets" width="150" height="150" class="size-thumbnail wp-image-3699" /></a><p class="wp-caption-text">Unity &#8211; Assets</p></div>
<p>In the previous article titled <a href="http://3dgep.com/?p=3246" title="Introduction to Unity">Introduction to Unity 3.5</a> I introduced the <a href="http://unity3d.com/" title="Unity" target="_blank">Unity</a> interface and we created a simple project that shows a rotating cube. In this article, I want to introduce some basic Unity concepts such as the Asset pipeline and the GameObject-Component model and introduce a few of the Components that <a href="http://unity3d.com/" title="Unity" target="_blank">Unity</a> provides.  I will not go into too much detail about the different components in this article (I will dedicate a different article for each of the more complex components such as Terrain, Particle Effects, Physics, Audio, and Scripts).</p>
<p><span id="more-3477"></span></p>
<div style="clear: both;"><div class='toc wptoc'>
<h2>Table of Contents</h2>
<ol class='toc-odd level-1'>
	<li>
		<a href="#Importing_Assets">Importing Assets</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#Models">Models</a>
				<ol class='toc-odd level-3'>
					<li>
						<a href="#Autodesk_3ds_Max">Autodesk 3ds Max</a>
					</li>
					<li>
						<a href="#Autodesk_Maya">Autodesk Maya</a>
					</li>
					<li>
						<a href="#Cinema_4D">Cinema 4D</a>
					</li>
					<li>
						<a href="#Cheetah3D">Cheetah3D</a>
					</li>
					<li>
						<a href="#Modo">Modo</a>
					</li>
					<li>
						<a href="#Blender">Blender</a>
					</li>
					<li>
						<a href="#Import_Settings">Import Settings</a>
						<ol class='toc-even level-4'>
							<li>
								<a href="#Scale_Factor">Scale Factor</a>
							</li>
							<li>
								<a href="#Mesh_Compression">Mesh Compression</a>
							</li>
							<li>
								<a href="#Optimize_Mesh">Optimize Mesh</a>
							</li>
							<li>
								<a href="#Generate_Colliders">Generate Colliders</a>
							</li>
							<li>
								<a href="#Swap_UVs">Swap UVs</a>
							</li>
							<li>
								<a href="#Generate_Lightmap_UVs">Generate Lightmap UVs</a>
							</li>
							<li>
								<a href="#Normals">Normals</a>
							</li>
							<li>
								<a href="#Tangents">Tangents</a>
							</li>
							<li>
								<a href="#Smoothing_Angle">Smoothing Angle</a>
							</li>
							<li>
								<a href="#Split_Tangents">Split Tangents</a>
							</li>
							<li>
								<a href="#Import_Materials">Import Materials</a>
							</li>
							<li>
								<a href="#Material_Naming">Material Naming</a>
							</li>
							<li>
								<a href="#Material_Search">Material Search</a>
							</li>
							<li>
								<a href="#Animations_-_Generation">Animations - Generation</a>
							</li>
							<li>
								<a href="#Bake_Animations">Bake Animations</a>
							</li>
							<li>
								<a href="#Animation_Wrap_Mode">Animation Wrap Mode</a>
							</li>
							<li>
								<a href="#Split_Animations">Split Animations</a>
							</li>
							<li>
								<a href="#Animation_Compression">Animation Compression</a>
							</li>
							<li>
								<a href="#Animation_Compression_Errors">Animation Compression Errors</a>
							</li>
						</ol>
</ol>
					<li>
						<a href="#Textures">Textures</a>
						<ol class='toc-odd level-3'>
							<li>
								<a href="#Import_Settings_1">Import Settings</a>
								<ol class='toc-even level-4'>
									<li>
										<a href="#Texture">Texture</a>
									</li>
									<li>
										<a href="#Normal_Map">Normal Map</a>
									</li>
									<li>
										<a href="#GUI">GUI</a>
									</li>
									<li>
										<a href="#Reflection">Reflection</a>
									</li>
									<li>
										<a href="#Cookie">Cookie</a>
									</li>
									<li>
										<a href="#Lightmaps">Lightmaps</a>
									</li>
									<li>
										<a href="#Advanced">Advanced</a>
									</li>
								</ol>
</ol>
							<li>
								<a href="#Audio">Audio</a>
							</li>
							<li>
								<a href="#Video">Video</a>
							</li>
							<li>
								<a href="#Text">Text</a>
							</li>
						</ol>
					<li>
						<a href="#GameObject">GameObject</a>
						<ol class='toc-even level-2'>
							<li>
								<a href="#Searching_for_GameObjects">Searching for GameObjects</a>
								<ol class='toc-odd level-3'>
									<li>
										<a href="#Assign_by_Reference">Assign by Reference</a>
									</li>
									<li>
										<a href="#Find_by_Tag">Find by Tag</a>
									</li>
									<li>
										<a href="#Find_by_Name">Find by Name</a>
									</li>
								</ol>
</ol>
							<li>
								<a href="#Prefabs">Prefabs</a>
								<ol class='toc-even level-2'>
									<li>
										<a href="#Creating_Prefabs">Creating Prefabs</a>
									</li>
								</ol>
							<li>
								<a href="#Components">Components</a>
								<ol class='toc-even level-2'>
									<li>
										<a href="#Animation_Components">Animation Components</a>
										<ol class='toc-odd level-3'>
											<li>
												<a href="#Animation">Animation</a>
											</li>
											<li>
												<a href="#Animation_Clip">Animation Clip</a>
											</li>
										</ol>
									<li>
										<a href="#Audio_Components">Audio Components</a>
										<ol class='toc-odd level-3'>
											<li>
												<a href="#Audio_Listener">Audio Listener</a>
											</li>
											<li>
												<a href="#Audio_Source">Audio Source</a>
											</li>
										</ol>
									<li>
										<a href="#Effects_Components">Effects Components</a>
										<ol class='toc-odd level-3'>
											<li>
												<a href="#Particle_System_Shuriken">Particle System (Shuriken)</a>
											</li>
											<li>
												<a href="#Halo">Halo</a>
											</li>
											<li>
												<a href="#Lens_Flare">Lens Flare</a>
											</li>
											<li>
												<a href="#Line_Renderer">Line Renderer</a>
											</li>
											<li>
												<a href="#Trail_Renderer">Trail Renderer</a>
											</li>
											<li>
												<a href="#Projector">Projector</a>
											</li>
										</ol>
									<li>
										<a href="#Mesh_Components">Mesh Components</a>
										<ol class='toc-odd level-3'>
											<li>
												<a href="#Mesh_Filter">Mesh Filter</a>
											</li>
											<li>
												<a href="#Mesh_Renderer">Mesh Renderer</a>
											</li>
											<li>
												<a href="#Skinned_Mesh_Renderer">Skinned Mesh Renderer</a>
											</li>
											<li>
												<a href="#Text_Mesh">Text Mesh</a>
											</li>
										</ol>
									<li>
										<a href="#Rendering_Components">Rendering Components</a>
										<ol class='toc-odd level-3'>
											<li>
												<a href="#Camera">Camera</a>
											</li>
											<li>
												<a href="#Flare_Layer">Flare Layer</a>
											</li>
											<li>
												<a href="#GUI_Layer">GUI Layer</a>
											</li>
											<li>
												<a href="#GUI_Text">GUI Text</a>
											</li>
											<li>
												<a href="#GUI_Texture">GUI Texture</a>
											</li>
											<li>
												<a href="#Light">Light</a>
											</li>
											<li>
												<a href="#Light_Probe_Group">Light Probe Group</a>
											</li>
											<li>
												<a href="#Occlusion_Area_Pro_Only">Occlusion Area (Pro Only)</a>
											</li>
											<li>
												<a href="#Occlusion_Portals">Occlusion Portals</a>
											</li>
											<li>
												<a href="#Skybox">Skybox</a>
											</li>
											<li>
												<a href="#Level_of_Detail_Pro_Only">Level of Detail (Pro Only)</a>
											</li>
										</ol>
									<li>
										<a href="#Physics_Components">Physics Components</a>
										<ol class='toc-odd level-3'>
											<li>
												<a href="#Physics">Physics</a>
												<ol class='toc-even level-4'>
													<li>
														<a href="#Rigidbody">Rigidbody</a>
													</li>
													<li>
														<a href="#Character_Controller">Character Controller</a>
													</li>
													<li>
														<a href="#Consant_Force">Consant Force</a>
													</li>
												</ol>
											<li>
												<a href="#Colliders">Colliders</a>
												<ol class='toc-even level-4'>
													<li>
														<a href="#Sphere_Collider">Sphere Collider</a>
													</li>
													<li>
														<a href="#Box_Collider">Box Collider</a>
													</li>
													<li>
														<a href="#Capsule_Collider">Capsule Collider</a>
													</li>
													<li>
														<a href="#Mesh_Collider">Mesh Collider</a>
													</li>
													<li>
														<a href="#Wheel_Collider">Wheel Collider</a>
													</li>
												</ol>
</ol>
</ol>
											<li>
												<a href="#Conclusion">Conclusion</a>
											</li>
											<li>
												<a href="#Exercise">Exercise</a>
											</li>
											<li>
												<a href="#References">References</a>
											</li>
</ol>
</div>
<div class='wptoc-end'>&nbsp;</div></div>
<span id="Importing_Assets"><h1>Importing Assets</h1></span>
<p>Unity has probably the most comprehensive support for different asset types that you would want to use in your game. Unity has native (built-in) support for many file formats for model files, texture files, audio files, video files, and text files as can be seen from the table below:</p>
<table>
<tr>
<th>Type</th>
<th>External Package</th>
<th>Extension</th>
<th>Requirements</th>
<tr>
<td rowspan="12" style="vertical-align: middle;">3D Model</td>
<td nowrap="nowrap">Maya</td>
<td align="center" nowrap>.ma &amp; .mb</td>
<td>Must have Maya 8.0 or newer installed.</td>
</tr>
<tr>
<td nowrap="nowrap">3D Studio Max</td>
<td align="center" nowrap="nowrap">.max</td>
<td>Must have 3D Studio Max installed.</td>
</tr>
<tr>
<td nowrap="nowrap">Cheetah3D</td>
<td align="center" nowrap="nowrap">.jas</td>
<td>Must have Cheetah3D 2.6 or newer installed.</td>
</tr>
<tr>
<td nowrap="nowrap">Cinema 4D</td>
<td align="center" nowrap="nowrap">.c4d</td>
<td>Must have Cinema 4D 8.5 or newer installed.</td>
</tr>
<tr>
<td nowrap="nowrap">Modo</td>
<td align="center" nowrap="nowrap">.lxo</td>
<td>Must have Modo 501 or newer installed.</td>
</tr>
<tr>
<td nowrap="nowrap">Lightwave</td>
<td align="center" nowrap="nowrap">.fbx</td>
<td>Models must be exported to FBX format.</td>
</tr>
<tr>
<td nowrap="nowrap">Blender</td>
<td align="center" nowrap="nowrap">.blend</td>
<td>Must have Blender 2.45-2.49 or 2.58 or newer (versions 2.50-2.57 broke the FBX exporter in Blender).</td>
</tr>
<tr>
<td nowrap="nowrap">COLLADA</td>
<td align="center" nowrap="nowrap">.dae</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td nowrap="nowrap">Autodesk FBX</td>
<td align="center" nowrap="nowrap">.fbx</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td nowrap="nowrap">Wavefront</td>
<td align="center" nowrap="nowrap">.obj</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td nowrap="nowrap">3D Studio</td>
<td align="center" nowrap="nowrap">.3ds</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td nowrap="nowrap">Drawing Interchange</td>
<td align="center" nowrap="nowrap">.dfx</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td rowspan="2" style="vertical-align: middle;">Texture</td>
<td nowrap="nowrap">Photoshop</td>
<td align="center" nowrap="nowrap">.psd</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td nowrap="nowrap">Other Image Formats</td>
<td align="center">.jpg, .png, gif, .bmp, .tga, .iff, .pict, .dds, and more&#8230;</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td rowspan="3" style="vertical-align: middle;">Audio</td>
<td nowrap="nowrap">MP3</td>
<td align="center">.mp3</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td nowrap="nowrap">Ogg Vorbis</td>
<td align="center">.ogg</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td nowrap="nowrap">Other Audio Formats</td>
<td align="center">.aiff, .wav, .mod, .it, .sm3, and more&#8230;</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td style="vertical-align: middle;">Video</td>
<td nowrap="nowrap">Video Formats</td>
<td align="center">.mov, .avi, .asf, .mpg, .mpeg, .mp4</td>
<td>Video files are transcoded by Unity.</td>
</tr>
<tr>
<td style="vertical-align: middle;">Text</td>
<td nowrap="nowrap">Text File Formats</td>
<td align="center">.txt, .htm, .html, .xml, .bytes</td>
<td>Text files are not converted.</td>
</tr>
</table>
<p>[<a href="http://unity3d.com/unity/editor/importing" title="Unity - Asset Importing" target="_blank">Source</a>]</p>
<p>In most cases, you can simply drop the game asset in the <strong>Assets</strong> folder in your game project and Unity will automatically import it into the editor.</p>
<span id="Models"><h2>Models</h2></span>
<p>Unity has native support for some model formats that do not require 3rd-party tools to be installed. The formats include <strong>Autodesk FBX</strong> (.FBX), <strong>Collada</strong> (.DAE), <strong>Autodesk 3D Studio</strong> (.3DS), <strong>AutoCAD Drawing Exchange Format</strong> (.DXF), and <strong>Wavefront Geometry Object File</strong> (.OBJ). Any modeling package that export export (or work directly with) one of these model formats can be natively supported by Unity&#8217;s built-in model importers.</p>
<p>Some file formats however require 3rd-party software to be installed before Unity will be able to import those files. These file formats include <strong>Autodesk 3ds Max and Maya</strong> (.max, .ma, .mb), <strong>Maxon Cinema4D</strong> (.c4d), <strong>Cheetah3D</strong> (.jas), <strong>Modo</strong> (.lxo), and <strong>Blender</strong> (.blend).</p>
<span id="Autodesk_3ds_Max"><h3>Autodesk 3ds Max</h3></span>
<p><div id="attachment_3485" class="wp-caption alignleft" style="width: 160px"><a href="http://www.autodesk.com/3dsmax"><img src="http://3dgep.com/wp-content/uploads/2012/07/3ds-Max-Icon-150x150.png" alt="Autodesk 3ds Max Icon" title="Autodesk 3ds Max Icon" width="150" height="150" class="size-thumbnail wp-image-3485" /></a><p class="wp-caption-text">Autodesk 3ds Max Icon</p></div><br />
Unity can import <a href="http://www.autodesk.com/3dsmax" title="3ds Max" target="_blank">3ds Max</a> files (.max) as long as you have <a href="http://www.autodesk.com/3dsmax" title="3ds Max" target="_blank">Autodesk&#8217;s 3ds Max</a> software installed.</p>
<p>Unity will import the following information from the 3ds Max files [<a href="http://docs.unity3d.com/Documentation/Manual/HOWTO-ImportObjectMax.html" title="Importing Objects from 3D Studio Max" target="_blank">source</a>]:</p>
<div style="clear:both;">
<ul>
<li>All nodes with position, rotation, and scale. Pivot points and names are also imported.</li>
<li>Meshes with vertex colors, normals and one or two UV sets.</li>
<li>Materials with diffuse texture and color. Multiple materials per mesh.</li>
<li>Animations</li>
<li>Bone based animations</li>
</ul>
</div>
<p>[<a href="http://docs.unity3d.com/Documentation/Manual/HOWTO-ImportObjectMax.html" title="Importing Objects from 3ds Max" target="_blank">Source</a>]</p>
<span id="Autodesk_Maya"><h3>Autodesk Maya</h3></span>
<div id="attachment_3483" class="wp-caption alignleft" style="width: 160px"><a href="http://www.autodesk.com/maya"><img src="http://3dgep.com/wp-content/uploads/2012/07/Maya-Icon-150x150.png" alt="Autodesk Maya Icon" title="Autodesk Maya Icon" width="150" height="150" class="size-thumbnail wp-image-3483" /></a><p class="wp-caption-text">Autodesk Maya Icon</p></div>
<p>Unity will import <a href="http://www.autodesk.com/maya" title="Maya" target="_blank">Maya</a> model files (.ma, .mb) as long as you have <a href="http://www.autodesk.com/maya" title="Maya" target="_blank">Autodesk&#8217;s Maya</a> software installed.</p>
<p>Unity will import the following information from the Maya files [<a href="http://docs.unity3d.com/Documentation/Manual/HOWTO-ImportObjectMaya.html" title="Importing Objects from Maya" target="_blank">source</a>]:</p>
<div style="clear:both;">
<ul>
<li>All nodes with position, rotation and scale. Pivot points and Names are also imported.</li>
<li>Meshes with vertex colors, normals and up to 2 UV sets.</li>
<li>Materials with Texture and diffuse color. Multiple materials per mesh.</li>
<li>Animations FK &#038; IK.</li>
<li>Bone-based animations.</li>
</ul>
<p>Unity will not import blend shapes. Use bone-based animation instead.</p>
</div>
<p>[<a href="http://docs.unity3d.com/Documentation/Manual/HOWTO-ImportObjectMaya.html" title="Importing Objects From Maya" target="_blank">Source</a>]</p>
<span id="Cinema_4D"><h3>Cinema 4D</h3></span>
<p><div id="attachment_3544" class="wp-caption alignleft" style="width: 160px"><a href="http://www.maxon.net/en/home.html"><img src="http://3dgep.com/wp-content/uploads/2012/07/C4D-R13-Logo-512x512-150x150.png" alt="Cinema4D Icon" title="Cinema4D Icon" width="150" height="150" class="size-thumbnail wp-image-3544" /></a><p class="wp-caption-text">Cinema4D Icon</p></div><br />
Unity will import <a href="http://www.maxon.net/" title="Maxon Cinema 4D" target="_blank">Maxon Cinema 4D</a> (.c4d) files as long as you have the <a href="http://www.maxon.net/" title="Maxon Cinema 4D" target="_blank">Maxon Cinema 4D</a> software installed.</p>
<p>Unity will import the following information from the Cinema 4D model files [<a href="http://docs.unity3d.com/Documentation/Manual/HOWTO-ImportObjectCinema4D.html" title="Importing Objects from Cinema 4D" target="_blank">source</a>]:</p>
<div style="clear:both;">
<ul>
<li>All objects with position, rotation and scale. Pivot points and Names are also imported.</li>
<li>Meshes with UVs and normals.</li>
<li>Materials with Texture and diffuse color. Multiple materials per mesh.</li>
<li>Animations FK (IK needs to be manually baked).</li>
<li>Bone-based animations.</li>
</ul>
</div>
<p>Unity does not support Point Level Animations (PLA). Use bone-based animations instead.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Manual/HOWTO-ImportObjectCinema4D.html" title="Importing Objects From Cinema 4D" target="_blank">Source</a>]</p>
<span id="Cheetah3D"><h3>Cheetah3D</h3></span>
<div id="attachment_3547" class="wp-caption alignleft" style="width: 160px"><a href="http://www.cheetah3d.com/"><img src="http://3dgep.com/wp-content/uploads/2012/07/Cheetah3D5Logo-150x150.png" alt="Cheetah3D Logo" title="Cheetah3D Logo" width="150" height="150" class="size-thumbnail wp-image-3547" /></a><p class="wp-caption-text">Cheetah3D Logo</p></div>
<p>Unity will import <a href="http://www.cheetah3d.com/" title="Cheetah3D" target="_blank">Cheetah3D</a> (.jas) files as long as you have the <a href="http://www.cheetah3d.com/" title="Cheetah3D" target="_blank">Cheetah3D</a> software installed.</p>
<p>Unity will import the following information from a Cheetah3D file [<a href="http://docs.unity3d.com/Documentation/Manual/HOWTO-ImportObjectCheetah3D.html" title="Importing Objects from Cheetah3D" target="_blank">source</a>]:</p>
<div style="clear:both;">
<ul>
<li>All nodes with position, rotation and scale. Pivot points and Names are also imported.</li>
<li>Meshes with vertices, polygons, triangles, UV&#8217;s and Normals.</li>
<li>Animations.</li>
<li>Materials with diffuse color and textures.</li>
</ul>
</div>
<p>[<a href="http://docs.unity3d.com/Documentation/Manual/HOWTO-ImportObjectCheetah3D.html" title="Importing Objects From Cheetah3D" target="_blank">Source</a>]</p>
<span id="Modo"><h3>Modo</h3></span>
<div id="attachment_3481" class="wp-caption alignleft" style="width: 160px"><a href="http://www.luxology.com/"><img src="http://3dgep.com/wp-content/uploads/2012/07/Modo-Icon-150x150.png" alt="Luxology Modo Icon" title="Luxology Modo Icon" width="150" height="150" class="size-thumbnail wp-image-3481" /></a><p class="wp-caption-text">Luxology Modo Icon</p></div>
<p>Unity will import <a href="http://www.luxology.com/" title="Luxology Modo" target="_blank">Modo</a> model files as long as you have the Modo 501 or newer software installed.</p>
<p>Unity will import the following information [<a href="http://docs.unity3d.com/Documentation/Manual/HOWTO-ImportObjectModo.html" title="Importing Objects from Modo" target="_blank">source</a>]:</p>
<div style="clear:both;">
<ul>
<li>All nodes with position, rotation and scale. Pivot points and names are also imported.</li>
<li>Meshes with vertices, normals and UVs.</li>
<li>Materials with Texture and diffuse color. Multiple materials per mesh.</li>
<li>Animations.</li>
</ul>
</div>
<p>[<a href="http://docs.unity3d.com/Documentation/Manual/HOWTO-ImportObjectModo.html" title="Importing Objects from Modo" target="_blank">Source</a>]</p>
<span id="Blender"><h3>Blender</h3></span>
<div id="attachment_3482" class="wp-caption alignleft" style="width: 160px"><a href="http://www.blender.org/"><img src="http://3dgep.com/wp-content/uploads/2012/07/Blender-Icon-150x150.png" alt="Blender Icon" title="Blender Icon" width="150" height="150" class="size-thumbnail wp-image-3482" /></a><p class="wp-caption-text">Blender Icon</p></div>
<p>Unity will automatically import <a href="http://www.blender.org/" title="Blender" target="_blank">Blender</a> (.blend) files as long as you have <a href="http://www.blender.org/" title="Blender" target="_blank">Blender</a> 2.58 or later installed.</p>
<p>Unity will import the following information [<a href="http://docs.unity3d.com/Documentation/Manual/HOWTO-ImportObjectBlender.html" title="Importing Objects from Blender" target="_blank">source</a>]:</p>
<div style="clear:both;">
<ul>
<li>All nodes with position, rotation and scale. Pivot points and Names are also imported.</li>
<li>Meshes with vertices, polygons, triangles, UVs, and normals.</li>
<li>Bones.</li>
<li>Skinned Meshes.</li>
<li>Animations.</li>
</ul>
</div>
<p>[<a href="http://docs.unity3d.com/Documentation/Manual/HOWTO-ImportObjectBlender.html" title="Importing Objects from Blender" target="_blank">Source</a>]</p>
<span id="Import_Settings"><h3>Import Settings</h3></span>
<p>The <strong>Import Settings</strong> will be displayed in the <strong>Inspector</strong> view when a <strong>Mesh</strong> asset is selected in the <strong>Project</strong> view.</p>
<div id="attachment_3496" class="wp-caption alignnone" style="width: 346px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Model-Importer.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Model-Importer.gif" alt="Unity - Model Import Settings" title="Unity - Model Import Settings" width="336" height="931" class="size-full wp-image-3496" /></a><p class="wp-caption-text">Unity &#8211; Model Import Settings</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Manual/Meshes.html" title="Meshes" target="_blank">Source</a>]</p>
<span id="Scale_Factor"><h4>Scale Factor</h4></span>
<p>Generally, Unity prefers the world scale of 1 unit per meter as this is the natural units to be used by the physics system. However, an artist may want to work in a different scale (say 1 cm per world unit, or 1 inch per world unit).</p>
<p>Use the <strong>Scale Factor</strong> import setting to control how Unity will scale the imported mesh.</p>
<span id="Mesh_Compression"><h4>Mesh Compression</h4></span>
<p>If you are concerned about the files size of the imported meshes (for example, your models will be used on mobile platforms), you can enable mesh compression.  There are 4 levels of mesh compression:</p>
<ul>
<li><strong>Off</strong>: No mesh compression occurs, models are stored with all data intact.</li>
<li><strong>Low</strong>: Some compression occurs. No artifacts should occur.</li>
<li><strong>Medium</strong>: More compression occurs. Some artifacts may occur.</li>
<li><strong>High</strong>: High compression. May cause artifacts in the compressed mesh.</li>
</ul>
<p>A general rule of thumb is to use the highest level of compression as long as no visible artifacts occur.</p>
<span id="Optimize_Mesh"><h4>Optimize Mesh</h4></span>
<p>With the <strong>Optimize Mesh</strong> option enabled, Unity will reorganize the vertices in the mesh for optimized rendering.</p>
<span id="Generate_Colliders"><h4>Generate Colliders</h4></span>
<p>With the <strong>Generate Colliders</strong> option enabled, Unity will generate a <strong>Mesh Collider</strong> component during mesh import.</p>
<p>This option should only be specified on static objects (objects that will not be moved very often).</p>
<span id="Swap_UVs"><h4>Swap UVs</h4></span>
<p>This option will swap the primary and secondary UV channels. This is useful if the lightmap and the diffuse UV channels are not correct during import.</p>
<span id="Generate_Lightmap_UVs"><h4>Generate Lightmap UVs</h4></span>
<p>For static objects that will not be moving very often, it might be useful to disable dynamic lights on those objects and only apply a static (pre rendered) lightmap. Unity can generate a set of UVs that can be used to apply a static lightmap texture to the model.</p>
<p>This option should be disabled for objects that will be moving in the scene and will not have a lightmap applied to them.</p>
<span id="Normals"><h4>Normals</h4></span>
<p>Unity can generate surface normals for models if the original model does not define them.</p>
<p>Usually you will want to Import the normals that are already on the mesh.</p>
<p>Surface normals are only needed on models that will be dynamically lit at run-time. Static models that will only have lightmaps applied to them do not need to have surface normals and setting this option to None can reduce the size of the imported model.</p>
<span id="Tangents"><h4>Tangents</h4></span>
<p>Tangent vectors are needed only on models that have normal maps applied to them.  For models that will not use normal maps it is best to disable this setting to reduce the size of the imported model.</p>
<span id="Smoothing_Angle"><h4>Smoothing Angle</h4></span>
<p>The <strong>Smoothing Angle</strong> slider becomes active if you specify <strong>Calculate</strong> for the <strong>Normals</strong> setting.</p>
<p>This value will smooth vertex normals by averaging the vertex normals of neighboring vertices as long as edge between the vertices is less than the value of <strong>Smoothing Angle</strong>.  Edges whose angle is greater than this value will appear sharp.</p>
<p>This parameter is measured in degrees.</p>
<span id="Split_Tangents"><h4>Split Tangents</h4></span>
<p>Enable the <strong>Split Tangents</strong> option if normal map lighting is broken by seams on your mesh.</p>
<span id="Import_Materials"><h4>Import Materials</h4></span>
<p>Disable the <strong>Import Materials</strong> option if you don&#8217;t want Unity to generate materials for your models. Disabling this option after the model has been initially imported will not delete the material that were previously generated.</p>
<p>If this option is disabled, Unity will apply the default-diffuse material instead.</p>
<span id="Material_Naming"><h4>Material Naming</h4></span>
<p>This option is only available if the <strong>Import Materials</strong> option is enabled.</p>
<p>This setting determines how generated materials are named.</p>
<ul>
<li><strong>By Base Texture Name</strong>: The name of the texture that is applied to the primary (diffuse) texture stage is used to name the generated material in Unity.</li>
<li><strong>From Model&#8217;s Material</strong>: The material name that is applied to the imported mesh will be used to name the generated material in Unity.</li>
<li><strong>Model Name + Model&#8217;s Material</strong>: The model&#8217;s original file name and the mesh&#8217;s material name will be combined to produce the generated material&#8217;s file name. This option is useful to reduce name clashing if you have many models with the same material names applied to them.</li>
</ul>
<span id="Material_Search"><h4>Material Search</h4></span>
<p>The <strong>Material Search</strong> option controls how Unity will search for a material in the project.</p>
<ul>
<li><strong>Local</strong>: Unity will only look for a material that matches this model in the folder called <strong>Materials</strong> that exists in the same directory as the model itself.</li>
<li><strong>Recursive-Up</strong>: Unity will look for a material for this model first in the local folder and continually search parent directory&#8217;s <strong>Materials</strong> folders until it finds a matching material.</li>
<li><strong>Project-Wide</strong>: Unity will search every folder in the project for a matching material.</li>
</ul>
<p>If Unity does not find a matching material file for the current model&#8217;s meshes, then it will generate a new material file in a folder called &#8220;Materials&#8221; at the same level as the model file itself using the naming convention specified.</p>
<span id="Animations_8211_Generation"><h4>Animations &#8211; Generation</h4></span>
<p>Controls how animations are imported.</p>
<ul>
<li><strong>Don&#8217;t Import</strong>: No animations or skinning information is imported.</li>
<li><strong>Store in Original Roots</strong>: Animations are stored in the root objects of your animation package. These may be different that the root node of the imported model if the original model file contains several animated meshes.</li>
<li><strong>Store in Nodes</strong>: Animations are stored together with the objects they animate. Use this setting if you have a complex animation setup and want full scripting control.</li>
<li><strong>Store in Root</strong>: The animations are stored in the model&#8217;s root node. This is used for animations with a hierarchy (such as a skeletal animated character).</li>
</ul>
<span id="Bake_Animations"><h4>Bake Animations</h4></span>
<p>If your animation contains inverse-kinematics (IK) or simulation in your animation package, Unity will convert it to forward-kinematics (FK) on import. This option is only available for Maya, 3ds Max, and Cinema4D model files.</p>
<span id="Animation_Wrap_Mode"><h4>Animation Wrap Mode</h4></span>
<p>The <strong>Animation Wrap Mode</strong> drop-down box allows you to select the default wrap mode for imported animations.</p>
<p>The different options are:</p>
<ul>
<li><strong>Default</strong>: Uses the wrap-mode specified in the Animation split options (described below).</li>
<li><strong>Once</strong>: The animation is played through once and then stops.</li>
<li><strong>Loop</strong>: The animation will restart automatically after it has reached the last frame.</li>
<li><strong>PingPong</strong>: The animation will play in reverse after it has reached the last frame, then play forward after it has reached the first frame again, and then repeat.  This is useful for pendulum or oscillating animations.</li>
<li><strong>Clamp Forever</strong>: The animation is played through once but the last frame is repeated indefinitely.</li>
</ul>
<span id="Split_Animations"><h4>Split Animations</h4></span>
<p>If you have multiple animations described in a single animation sequence, you can split the different animations into multiple animation clips.</p>
<p>Each animation clip defines the following properties:</p>
<ul>
<li><strong>Name</strong>: The name that identifies the animation clip. This name is used to play the animation clip in scripts.</li>
<li><strong>Start</strong>: The first frame in the main sequence for this clip.</li>
<li><strong>End</strong>: The last frame in the main sequence for this clip.</li>
<li><strong>WrapMode</strong>: The wrap mode for this clip. Wrap modes were described above.</li>
<li><strong>Loop</strong>: Depending on how the animation was created, one extra frame of animation may be required for the split clip to loop properly. If your looping animation doesn&#8217;t look correct, try enabling this option</li>
</ul>
<span id="Animation_Compression"><h4>Animation Compression</h4></span>
<p>The <strong>Animation Compression</strong> drop-down box allows Unity to reduce the number of keyframes needed to represent the animation.</p>
<p>The options are:</p>
<ul>
<li><strong>Off</strong>: No compression or reduction of keyframes occurs.</li>
<li><strong>Keyframe Reduction</strong>: Unity will try to reduce the required number of keyframes during import.  Unity will use the <strong>Animation Compression Errors</strong> options listed below to determine which keyframes are eliminated.</li>
<li><strong>Keyframe Reduction and Compression</strong>: This is the same as <strong>Keyframe Reduction</strong> but also compresses the animation data stored on disk. This option does not effect the run-time memory requirements.</li>
</ul>
<span id="Animation_Compression_Errors"><h4>Animation Compression Errors</h4></span>
<p>These options determine how Unity performs the keyframe reduction.</p>
<ul>
<li><strong>Rotation Error</strong>: Defines the maximum angle deviation allowed in degrees. Rotation keyframes with an angular deviation less than this are allowed to be removed.</li>
<li><strong>Position Error</strong>: Defines the maximum change in distance between keyframes that are allowed to be removed.</li>
<li><strong>Scale Error</strong>: Defines the maximum delta deviation allowed in a scale keyframe for that keyframe to be considered for reduction.</li>
</ul>
<span id="Textures"><h2>Textures</h2></span>
<p>Unity has native support for almost all texture image formats.</p>
<ul>
<li>JPEG (.jpg, .jpeg)</li>
<li>PNG (.png)</li>
<li>GIF (.gif)</li>
<li>BMP (.bmp)</li>
<li>TGA (.tga, .tpic)</li>
<li>PICT (.pict, .pct, .pic)</li>
<li>PSD (.psd) Adobe PhotoShop Document Format. Visible layers will be compressed and merged.</li>
<li>And more&#8230;</li>
</ul>
<p>Textures will be imported automatically by Unity and converted to an optimized texture format based on the settings in the <strong>Texture Importer</strong>.  Unity even supports multi-layered Phtoshop and TIFF files. Visible layers will be automatically flattened on import.  You can make changes to these file in your favorite image editor and the modified files will be automatically re-imported and you will be able to see the modifications instantly in the Unity editor.</p>
<span id="Import_Settings_1"><h3>Import Settings</h3></span>
<p>Selecting an image in the Project view will allow you to adjust the import settings for that image.</p>
<p>There are several different texture types and each type has a different set of input options.</p>
<ul>
<li><strong>Texture</strong>: This is the most common texture type and it is generally used for textures that will be mapped to 3D models or animated characters.</li>
<li><strong>Normal Map</strong>: This is a special form of the <strong>Texture</strong> type. It is used to import a texture that will be used to define the surface normals across the faces of a 3D model.</li>
<li><strong>GUI</strong>: This texture type should be used on images that will be used for HUD or GUI elements (like menus or on-screen displays).</li>
<li><strong>Reflection</strong>: This texture type should be applied to images that represent a reflection map (also known as a cube map or environment map).</li>
<li><strong>Cookie</strong>: This texture type should be applied to images of cookies.  Just kidding. A light cookie is applied to dynamic lights in the scene and can be used to modify the shape (or pattern) of the light.</li>
<li><strong>Advanced</strong>: This type allows you to have more precise control over how your texture is imported.</li>
</ul>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Texture2D.html" title="Unity - Texture 2D" target="_blank">Source</a>]</p>
<span id="Texture"><h4>Texture</h4></span>
<p>The <strong>Texture</strong> type provides the most common set of import options.</p>
<div id="attachment_3508" class="wp-caption alignnone" style="width: 322px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Texture-Import-Settings-Texture.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Texture-Import-Settings-Texture.png" alt="Unity - Texture Import Settings (Texture)" title="Unity - Texture Import Settings (Texture)" width="312" height="790" class="size-full wp-image-3508" /></a><p class="wp-caption-text">Unity &#8211; Texture Import Settings (Texture)</p></div>
<ul>
<li><strong>Alpha from Grayscale</strong>: Enabling this option will tell Unity to create an alpha channel for the imported texture based on the image&#8217;s grayscale value at each pixel.</li>
<li><strong>Wrap Mode</strong>: Specifies how to handle out-of-range texture coordinates with this texture.
<ul>
<li><strong>Repeat</strong>: The texture will be tiled.</li>
<li><strong>Clamp</strong>: The edges of the texture will be stretched infinently across the face of the polygon.</li>
</ul>
</li>
<li><strong>Filter Mode</strong>: Specifies how the pixels of the texture are blended when the texture is stretched or shrunk.
<ul>
<li><strong>Point</strong>: The closets pixel in the texture to the one being sampled is used. This results in blocky textures when viewed up-close but can improve performance.</li>
<li><strong>Bilinear</strong>: Neighboring pixels in the texture relative to the pixel being sampled are blended together based on distance to the sampled point. This results in blurry pixels when viewed up-close.</li>
<li><strong>Trilinear</strong>: Same as <strong>Bilinear</strong> but also blends the results from neighboring mip-map levels.</li>
</ul>
</li>
<li><strong>Aniso Level</strong>: This setting determines the level of anisotropic filtering that is applied when sampling this texture. Higher levels of filtering will produce better results but will be more GPU intensive. This setting should only be applied to textures that will be used for floors, roads, or the ground where the player will be viewing the texture from a sharp angle.</li>
</ul>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Texture2D.html" title="Unity - Texture 2D" target="_blank">Source</a>]</p>
<span id="Normal_Map"><h4>Normal Map</h4></span>
<p>The <strong>Normal Map</strong> texture type should be applied to standard normal maps or bump maps that Unity can convert to normal maps during import.</p>
<div id="attachment_3514" class="wp-caption alignnone" style="width: 322px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Texture-Import-Settings-Normal-Maps.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Texture-Import-Settings-Normal-Maps.png" alt="Unity - Texture Import Settings (Normal Maps)" title="Unity - Texture Import Settings (Normal Maps)" width="312" height="790" class="size-full wp-image-3514" /></a><p class="wp-caption-text">Unity &#8211; Texture Import Settings (Normal Maps)</p></div>
<ul>
<li><strong>Create from Grayscale</strong>: Select this option if you want to convert a grayscale image to a normal map.  The grayscale images are also called bump maps. White areas of the image represent elevated parts of the texture and normals will be computed based on the differences of neighboring pixels in the image.
<ul>
<li><strong>Bumpiness</strong>: This value controls how pronounced the changes in elevation will be. A value of 0 will produce a flat surface (no change in surface normal) and a value of 0.3 will generate very pronounced surface normals.</li>
<li><strong>Filtering</strong>: Determines how the normals are generated.
<ul>
<li><strong>Smooth</strong>: The normal map will appear smoothed.</li>
<li><strong>Sharp</strong>: The edges of the normal map will appear quite sharp. This might be useful for non-organic surface normals.</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>The last three settings (Wrap Mode, Filter Mode, and Aniso Level) are the same as for Texture type.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Texture2D.html" title="Unity - Texture 2D" target="_blank">Source</a>]</p>
<span id="GUI"><h4>GUI</h4></span>
<p>The <strong>GUI</strong> texture type should be applied to on-screen GUI or HUD elements. Unity will not scale non-power-of-two texture nor will it generate mip maps for GUI textures.</p>
<div id="attachment_3519" class="wp-caption alignnone" style="width: 322px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Texture-Import-Settings-GUI.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Texture-Import-Settings-GUI.png" alt="Unity - Texture Import Settings (GUI)" title="Unity - Texture Import Settings (GUI)" width="312" height="790" class="size-full wp-image-3519" /></a><p class="wp-caption-text">Unity &#8211; Texture Import Settings (GUI)</p></div>
<p>The only setting this texture type has is <strong>Filter Mode</strong> which is the same for the standard texture types.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Texture2D.html" title="Unity - Texture 2D" target="_blank">Source</a>]</p>
<span id="Reflection"><h4>Reflection</h4></span>
<p>The <strong>Reflection</strong> texture type is used to generate a reflection map (also known as an environment map or cube map).</p>
<div id="attachment_3521" class="wp-caption alignnone" style="width: 322px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Texture-Import-Settings-Reflection.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Texture-Import-Settings-Reflection.png" alt="Unity - Texture Import Settings (Reflection)" title="Unity - Texture Import Settings (Reflection)" width="312" height="790" class="size-full wp-image-3521" /></a><p class="wp-caption-text">Unity &#8211; Texture Import Settings (Reflection)</p></div>
<p>Unity can generate a reflection map texture from a simple 2D texture. Selecting the <strong>Reflection</strong> texture type will provide the <strong>Mapping</strong> option that specifies how the reflection map should be generated.</p>
<ul>
<li><strong>Sphere mapped</strong>: Maps the texture onto a sphere shape. Useful for generating environmental reflection maps.</li>
<li><strong>Cylindrical</strong>: Maps the texture to a cylinder shape. Useful for generating reflection maps that will be used on cylindrical shaped objects.</li>
<li><strong>Simple Sphere</strong>: Maps the texture to a sphere and the texture is deformed when rotated. This is useful if the original texture does not tile.</li>
<li><strong>Nice Sphere</strong>: Maps the texture to a sphere but maintains the original texture&#8217;s wrap mode.  Useful for textures that can be tiled.</li>
</ul>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Texture2D.html" title="Unity - Texture 2D" target="_blank">Source</a>]</p>
<span id="Cookie"><h4>Cookie</h4></span>
<p>A <strong>Cookie</strong> texture can be applied to a light component and will determine the shape of the light as it illuminates objects in the scene.  This is similar to a &#8220;cookie cutout&#8221; that is placed in front of the light to change the shape of the projected light.  This technique is typically used in films to achieve a desired lighting effect.</p>
<div id="attachment_3524" class="wp-caption alignnone" style="width: 322px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Texture-Import-Settings-Cookie.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Texture-Import-Settings-Cookie.png" alt="Unity - Texture Import Settings (Cookie)" title="Unity - Texture Import Settings (Cookie)" width="312" height="790" class="size-full wp-image-3524" /></a><p class="wp-caption-text">Unity &#8211; Texture Import Settings (Cookie)</p></div>
<p>The <strong>Light Type</strong> property can be <strong>Spotlight</strong>, <strong>Directional Light</strong>, and <strong>Point Light</strong>.</p>
<ul>
<li><strong>Spotlight</strong>: For Spotlight light types the cookie texture will be clamped so it&#8217;s a good idea to use a texture with a black.</li>
<li><strong>Directoinal</strong>: For Directional light types, the cookie texture will be tiled. In this case, you want to use a texture that can be tiled without seams. This is useful for creating a rolling cloud effect in your outdoor scenes.</li>
<li><strong>Point</strong>: For Point lights Unity will create a texture similar to a Reflection texture that can be used to mask the lighting from an omni-directional light source.  Selecting this option will make the <strong>Mapping</strong> option available. The <strong>Mapping</strong> option is the same as for the Reflection texture types.</li>
</ul>
<p>The <strong>Alpha from Grayscale</strong>, <strong>Filter Mode</strong>, and <strong>Aniso Level</strong> settings are the same as for the standard Texture type.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Texture2D.html" title="Unity - Texture 2D" target="_blank">Source</a>]</p>
<span id="Lightmaps"><h4>Lightmaps</h4></span>
<p>Select the Lightmap texture type if the texture will be applied to objects for static lighting.</p>
<div id="attachment_3525" class="wp-caption alignnone" style="width: 288px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Texture-Import-Settings-Lightmap.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Texture-Import-Settings-Lightmap.png" alt="Unity - Texture Import Settings (Lightmap)" title="Unity - Texture Import Settings (Lightmap)" width="278" height="771" class="size-full wp-image-3525" /></a><p class="wp-caption-text">Unity &#8211; Texture Import Settings (Lightmap)</p></div>
<p>The <strong>Filter Mode</strong> and <strong>Aniso Level</strong> settings are the same for the standard Texture type.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Texture2D.html" title="Unity - Texture 2D" target="_blank">Source</a>]</p>
<span id="Advanced"><h4>Advanced</h4></span>
<p>The <strong>Advanced</strong> texture type allows you to configure all of the texture import settings manually.</p>
<div id="attachment_3531" class="wp-caption alignnone" style="width: 313px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Texture-Import-Settings-Advanced.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Texture-Import-Settings-Advanced.png" alt="Unity - Texture Import Settings (Advanced)" title="Unity - Texture Import Settings (Advanced)" width="303" height="682" class="size-full wp-image-3531" /></a><p class="wp-caption-text">Unity &#8211; Texture Import Settings (Advanced)</p></div>
<ul>
<li><strong>Non Power of 2</strong>: If texture has non-power-of-two size, this will define a scaling behavior at import time.
<ul>
<li><strong>None</strong>: Texture will be padded to the next larger power-of-two size for use with GUITexture component.</li>
<li><strong>To nearest</strong>: Texture will be scaled to the nearest power-of-two size at import time. For instance 257&#215;511 texture will become 256&#215;512.</li>
<li><strong>To larger</strong>: Texture will be scaled to the next larger power-of-two size at import time. For instance 257&#215;511 texture will become 512&#215;512.</li>
<li><strong>To smaller</strong>: Texture will be scaled to the next smaller power-of-two size at import time. For instance 257&#215;511 texture will become 256&#215;256.</li>
</ul>
</li>
<li><strong>Generate Cube Map</strong>: Generates a cubemap from the texture using different generation methods.</li>
<li><strong>Read/Write Enabled</strong>: Select this to enable access to the texture data from scripts (GetPixels, SetPixels and other Texture2D functions). Note however that a copy of the texture data will be made, doubling the amount of memory required for texture asset. Use only if absolutely necessary. This is only valid for uncompressed and DTX compressed textures, other types of compressed textures cannot be read from.</li>
<li><strong>Import Type</strong>: Specify the type of import to apply to this texture.
<ul>
<li><strong>Default</strong>: Standard texture type. Use this for 2D textures and GUI texture types.  Selecting this option will make two other options available.
<ul>
<li><strong>Alpha from Grayscale</strong>:  Enabling this option will tell Unity to create an alpha channel for the imported texture based on the image&#8217;s grayscale value at each pixel.</li>
<li><strong>Bypass sRGB Sampling</strong>: Texture will not be converted from gamma space to linear space when sampled. Enable this option for GUI textures and look-up textures.</li>
</ul>
</li>
<li><strong>Normal Map</strong>:
<ul>
<li><strong>Create from Grayscale</strong>: Enable this to turn the color channels into a format suitable for normal mapping.</li>
<ul>
<li><strong>Bumpiness</strong>: Control the amount of bumpiness.</li>
<li> <strong>Filtering</strong>: Determine how the bumpiness is calculated.
<ul>
<li><strong>Sharp</strong>: Also known as a Sobel filter. this generates normal maps that are sharper than Standard.</li>
</ul>
<ul>
<li><strong> Smooth</strong>: This generates normal maps that are quite smooth.              </li>
</ul>
</li>
</ul>
</ul>
<li><strong>Lightmap</strong>: Select this if you want to use the texture as a lightmap.  </li>
</ul>
<li><strong>Generate Mip Maps</strong>: Select this to enable mip-map generation. Mip maps are smaller versions of the texture that get used when the texture is very small on screen.</li>
<li><strong>Correct Gamma</strong>: Select this to enable per-mip-level gamma correction.</li>
<li><strong>Border Mip Maps</strong>: Select this to avoid colors seeping out to the edge of the lower Mip levels. Used for light cookies.</li>
<li><strong>Mip Map Filtering</strong>: Two ways of mip map filtering are available to optimize image quality.
<ul>
<li><strong>Box</strong>: The simplest way to fade out the mipmaps &#8211; the mip levels become smoother and smoother as they go down in size.</li>
<li><strong>Kaiser</strong>: A sharpening Kaiser algorithm is run on the mip maps as they go down in size. If your textures are too blurry in the distance, try this option.</li>
</ul>
</li>
<li><strong>Fade Out Mips</strong>: Enable this to make the mipmaps fade to gray as the mip levels progress. This is used for detail maps. </li>
<ul>
<li><strong>Fade Range</strong>: The left most scroll is the first mip level to begin fading out at. The rightmost scroll defines the mip level where the texture is completely grayed out.</li>
</ul>
<li><strong>Wrap Mode</strong>: Specifies how to handle out-of-range texture coordinates with this texture.
<ul>
<li><strong>Repeat</strong>: The texture will be tiled.</li>
<li><strong>Clamp</strong>: The edges of the texture will be stretched infinently across the face of the polygon.</li>
</ul>
</li>
<li><strong>Filter Mode</strong>: Specifies how the pixels of the texture are blended when the texture is stretched or shrunk.
<ul>
<li><strong>Point</strong>: The closets pixel in the texture to the one being sampled is used. This results in blocky textures when viewed up-close but can improve performance.</li>
<li><strong>Bilinear</strong>: Neighboring pixels in the texture relative to the pixel being sampled are blended together based on distance to the sampled point. This results in blurry pixels when viewed up-close.</li>
<li><strong>Trilinear</strong>: Same as <strong>Bilinear</strong> but also blends the results from neighboring mip-map levels.</li>
</ul>
</li>
<li><strong>Aniso Level</strong>: This setting determines the level of anisotropic filtering that is applied when sampling this texture. Higher levels of filtering will produce better results but will be more GPU intensive. This setting should only be applied to textures that will be used for floors, roads, or the ground where the player will be viewing the texture from a sharp angle.</li>
</ul>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Texture2D.html" title="Unity - Texture 2D" target="_blank">Source</a>]</p>
<span id="Audio"><h2>Audio</h2></span>
<p>Unity has native support for many different audio formats.  Unity supports <strong>.aif</strong>, <strong>.wav</strong>, <strong>.mp3</strong>, and <strong>.ogg</strong>.</p>
<p>When you place an audio file somewhere in the Asset directory of your Unity game project, Unity will automatically import the audio file. Audio files can be imported in one of two formats.</p>
<ul>
<li><strong>Native</strong>: Uses the file&#8217;s native file format. In this case, the file will not be compressed. Use this for pre-compressed ambient audio files (already in MP3 or OGG compressed format) or if it is a small 1-shot sound effect.  Using this format, the file size on disk will be larger but the audio file will not need to be decoded at runtime before it can be played.</li>
<li><strong>Compressed</strong>: This will produce smaller audio files on disk but the file will need to be decompressed at runtime.  Unity will choose the compression algorithm based on the platform the game is being built for.  Audio files will be compressed using the Ogg Vorbis CODEC when targeting stand-alone PC or MAC or consoles (XBox360, PS3) or the MP3 CODEC will be used when targeting mobile platforms (Android, iOS, Web).</li>
</ul>
<p>Audio files are stored as <strong>AudioClip</strong>s in the Asset folder.  <strong>AudioClip</strong>s cannot be played directly but must be used in conjuction with an <strong>AudioSource</strong> component attached to a <strong>GameObject</strong> in the scene.  Before the sound can be heard, there must also be one active <strong>AudioListener</strong> component which is usually attached to the main camera in the scene.</p>
<p>The <strong>AudioClip</strong> is simply the container for the audio data that is used by the <strong>AudioSource</strong> component.  Selecting the audio file in the project view will show the import settings for that audio file in the Inspector view. </p>
<div id="attachment_3550" class="wp-caption alignnone" style="width: 313px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Audio-Import-Settings.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Audio-Import-Settings.png" alt="Unity - Audio Import Settings" title="Unity - Audio Import Settings" width="303" height="682" class="size-full wp-image-3550" /></a><p class="wp-caption-text">Unity &#8211; Audio Import Settings</p></div>
<ul>
<li><strong>Audio Format</strong>: The specific format that will be used for the sound at runtime.
<ul>
<li> <strong>Native</strong>: This option offers higher quality at the expense of larger file size and is best for very short sound effects.</li>
<li><strong>Compressed</strong>: The compression results in smaller files but with somewhat lower quality compared to native audio. This format is best for medium length sound effects and music.</li>
</ul>
</li>
<li><strong>3D Sound</strong>: If enabled, the sound will play back in 3D space. Both Mono and Stereo sounds can be played in 3D.</li>
<li><strong>Force to mono</strong>: If enabled, the audio clip will be down-mixed to a single channel sound.</li>
<li><strong>Load Type</strong>: The method Unity uses to load audio assets at runtime.
<ul>
<li><strong>Decompress on load</strong>: Audio files will be decompressed as soon as they are loaded. Use this option for smaller compressed sounds to avoid the performance overhead of decompressing on the fly. Be aware that decompressing sounds on load will use about ten times more memory than keeping them compressed, so don&#8217;t use this option for large files.</li>
<li><strong> Compressed in memory</strong>: Keep sounds compressed in memory and decompress while playing. This option has a slight performance overhead (especially for Ogg/Vorbis compressed files) so only use it for bigger files where decompression on load would use a prohibitive amount of memory.</li>
<li><strong> Stream from disc</strong>: Stream audio data directly from disc. The memory used by this option is typically a small fraction of the file size, so it is very useful for music or other very long tracks. For performance reasons, it is usually advisable to stream only one or two files from disc at a time but the number of streams that can comfortably be handled depends on the hardware.  </li>
</ul>
</li>
<li><strong> Hardware Decoding</strong>: (iOS only) On iOS devices, Apple&#8217;s hardware decoder can be used resulting in lower CPU overhead during decompression.</li>
<li><strong>Gapless looping</strong>: (Android/iOS only) Use this when compressing a seamless looping audio source file (in a non-compressed PCM format) to ensure perfect continuity is preserved at the seam.</li>
<li><strong>Compression (kbps)</strong>: Amount of Compression to be applied to a clip. Statistics about the compressed file size can be seen under the slider. A good approach to tuning this value is to drag the slider to a place that leaves the playback &quot;good enough&quot; while keeping the file small enough for your distribution requirements.
  </li>
</ul>
<p>[<a href="http://docs.unity3d.com/Documentation/Manual/AudioFiles.html" title="Unity - Audio Files" target="_blank">Source</a>]</p>
<span id="Video"><h2>Video</h2></span>
<div class="my-note">
Using video files as textures requires a Pro license.
</div>
<p>You can apply a video as a texture to a material using the <strong>MovieTexture</strong> asset component. Just drop a compatible video file in your project&#8217;s Asset folder and Unity will automatically create a <strong>MovieTexture</strong> asset component.</p>
<p>Unity supports any video format that can be played with <a href="http://www.apple.com/quicktime/download/" title="Download Quicktime" target="_blank">Quicktime</a> (<strong>.mov</strong>, <strong>.mpg</strong>, <strong>.mpeg</strong>, <strong>.mp4</strong>, <strong>.avi</strong>, <strong>.asf</strong>). Unity requires <a href="http://www.apple.com/quicktime/download/" title="Download Quicktime" target="_blank">Quicktime</a> to be pre-installed on your system.  If you don&#8217;t have it installed, you can download <a href="http://www.apple.com/quicktime/download/" title="Download Quicktime" target="_blank">Quicktime</a> from the Apple website here: <a href="http://www.apple.com/quicktime/download/" title="Download Quicktime" target="_blank">http://www.apple.com/quicktime/download/</a>.</p>
<div class="my-note">
Unity does not support <strong>.wmv</strong> files. These files will need to be transcoded to a compatible format to be used in your game project.  I suggest using <a href="http://www.adobe.com/products/mediaencoder.html" title="Adobe Media Encoder" target="_blank">Adobe Media Encoder</a> and transcode the files to the Quicktime <strong>.mov</strong> format.
</div>
<div id="attachment_3559" class="wp-caption alignnone" style="width: 326px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Import-Video-Settings.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Import-Video-Settings.png" alt="Unity - Video Import Settings" title="Unity - Video Import Settings" width="316" height="682" class="size-full wp-image-3559" /></a><p class="wp-caption-text">Unity &#8211; Video Import Settings</p></div>
<ul>
<li><strong>Bypass sRGB Sampling</strong>: Texture will not be converted from gamma space to linear space when sampled. Enable this option for GUI textures and look-up textures.</li>
<li><strong>Quality</strong>: Compression of the <a href="http://www.theora.org/" title="Theora video compression" target="_blank">Ogg Theora</a> video file. A higher value means higher quality, but larger file size.</li>
</ul>
<p>Movie textures will not be played automatically when the scene is opened. This must be done in script.</p>
<p>To play a movie file, attach the following script to a GameObject in your scene that has a MovieTexture applied to it&#8217;s material.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="PlayMovieTexture.js">
#pragma strict

private var movieTexture : MovieTexture;

function Start () 
{
	movieTexture = renderer.material.mainTexture as MovieTexture;
	if ( movieTexture != null )
	{
		movieTexture.loop = true;
	}
}

function Update () 
{
	if ( movieTexture != null )
	{
		if ( !movieTexture.isPlaying )
		{
			movieTexture.Play();			
		}
	}	
}
</pre>
</div>
<p>MovieTextures will also not loop by default and will not automatically stop when it has reached the last frame.  If you want the movie texture to loop, you must set the <strong>loop</strong> property on the <strong>MovieTexture</strong> to <strong>true</strong>.</p>
<p>When a video file is imported, Unity will import the audio track as a separate <strong>AudioClip</strong> asset component. </p>
<div id="attachment_3565" class="wp-caption alignnone" style="width: 226px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Movie-AudioClip.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Movie-AudioClip.png" alt="Unity - Movie AudioClip" title="Unity - Movie AudioClip" width="216" height="238" class="size-full wp-image-3565" /></a><p class="wp-caption-text">Unity &#8211; Movie AudioClip</p></div>
<p>To play the <strong>AudioClip</strong> together with the video, drag and drop the <strong>AudioClip</strong> asset component from the <strong>Project</strong> view onto a <strong>GameObject</strong> in the <strong>Hierarchy</strong> view that you want to act as the source (this does not necessarily have to be the same <strong>GameObject</strong> as the <strong>MovieTexture</strong> is applied to but it would make the most sense).  Unity will automatically create an <strong>AudioSource</strong> component on the <strong>GameObject</strong> and assign the <strong>AudioClip</strong> to the <strong>AudioSource</strong>. To play the <strong>AudioSource</strong> use the <strong>audio.Play()</strong> method on the GameObject that owns the <strong>AudioSource</strong>.  Don&#8217;t forget to set the <strong>loop</strong> property on the <strong>AudioSource</strong> to the same value of the <strong>loop</strong> property on the <strong>MovieTexture</strong>.</p>
<p>Here is an example script that will automatically play the <strong>AudioSource</strong> on a <strong>GameObject</strong> together with it&#8217;s <strong>MovieTexture</strong> (if it has one).</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="PlayMovieWithAudio.js">
#pragma strict

private var movieTexture : MovieTexture;

function Start () 
{
	movieTexture = renderer.material.mainTexture as MovieTexture;
	if ( movieTexture != null )
	{
		movieTexture.loop = true;
	}
	if ( audio != null )
	{
		audio.loop = true;
	}
}

function Update () 
{
    if ( movieTexture != null )
	{
		if ( !movieTexture.isPlaying )
		{
			movieTexture.Play();
			if ( audio != null )
			{
				audio.Play();
			}
		}
	}	
}
</pre>
</div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-MovieTexture.html" title="Unity - Movie Texture" target="_blank">Source</a>]</p>
<span id="Text"><h2>Text</h2></span>
<p>Unity also supports text file assets with extensions <strong>.txt</strong>, <strong>.html</strong>, <strong>.htm</strong>, <strong>.xml</strong>, and <strong>.bytes</strong> (binary text format).</p>
<div id="attachment_3569" class="wp-caption alignnone" style="width: 286px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Text-Asset.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Text-Asset.png" alt="Unity - Text Asset" title="Unity - Text Asset" width="276" height="431" class="size-full wp-image-3569" /></a><p class="wp-caption-text">Unity &#8211; Text Asset</p></div>
<p>Text files have no import options, they are used as-is.  However, <strong>TextAsset</strong>s are read-only. You cannot use a <strong>TextAsset</strong> to write data.  You can access the contents of a <strong>TextAsset</strong> using the <strong>text</strong> (read-only) property.</p>
<p>Binary data can be imported as a <strong>TextAsset</strong> asset as long as the file has the <strong>.bytes</strong> extension, Unity will treat it as a binary file.  The binary data can be accessed using the <strong>bytes</strong> (read-only) property of the <strong>TextAsset</strong>.</p>
<p>Unity will only publish referenced assets (An asset that is assigned to a public script variable or referenced by a component that is attached to a <strong>GameObject</strong>) however TextAssets may not be referenced by any script or component.  To ensure the TextAsset is published with your build, place the TextAsset in a special folder called <strong>Resources</strong>. Any assets in a folder called <strong>Resources</strong> will be published with your build and accessible using the <strong>Resources</strong> class.</p>
<p>For example, the following script will load a <strong>TextAsset</strong> and assign the binary data to a texture.  The name of the resource to load can be specified in the <strong>Inspector</strong> by modifying the <strong>Texture Name</strong> property.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="AssignTexture.js">
#pragma strict

public var textureName : String;

function Start () 
{
	// Load a binary asset from "Assets/Resources/[textureName].bytes"
	var imageData : TextAsset = Resources.Load( textureName );
	if ( imageData != null )
	{
		var newTexture : Texture2D = new Texture2D( 1, 1 );
		newTexture.LoadImage( imageData.bytes );
		renderer.material.mainTexture = newTexture;
	}

}
</pre>
</div>
<p>When loading resources in this way, you only need to specify the base name. You do not need to specify the full path or the extension of the file.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-TextAsset.html" title="Unity - Text Asset">Source</a>]</p>
<span id="GameObject"><h1>GameObject</h1></span>
<p>Every object in your scene is a <strong>GameObject</strong>. A <strong>GameObject</strong> can either be a visual object (such as a <strong>Mesh</strong>, <strong>Terrain</strong> or a <strong>Light</strong>) or a <strong>GameObject</strong> can simply be a parent node or a root node that is used to group other <strong>GameObject</strong>s that share some kind of relationship.</p>
<p>This type of hierarchical structure is also known as a Composite. This is a very powerful way to organize your complex scenes.</p>
<p><strong>GameObject</strong>s can also be used as logical entities which do not have any renderable component attached to them nor do they necessarily have any child <strong>GameObject</strong>s with renderable componenents.  In this case, a <strong>GameObject</strong> may only have Script components attached to them which can be used to control the logic of abstract game elements such as Unity&#8217;s internal Network functionality.</p>
<p>The image below shows an empty GameObject that has no components attached to it.</p>
<div id="attachment_3576" class="wp-caption alignnone" style="width: 748px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-GameObject.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-GameObject.png" alt="Unity - GameObject" title="Unity - GameObject" width="738" height="435" class="size-full wp-image-3576" /></a><p class="wp-caption-text">Unity &#8211; GameObject</p></div>
<p>A <strong>GameObject</strong> by itself is not very interesting. You must add at least one <strong>Component</strong> to a <strong>GameObject</strong> in order for it to have purpose.  For example, to make a <strong>GameObject</strong> act like a <strong>Light</strong>, you must attach a <strong>Light</strong> component to the <strong>GameObject</strong>.</p>
<p>Every <strong>GameObject</strong> has the following properties:</p>
<ul>
<li><strong>Name</strong>: The name that is used to identify the <strong>GameObject</strong>. The Name property does not have to be unique in the scene unless you need to need to access the <strong>GameObject</strong> from a script.</li>
<li><strong>Tag</strong>: The <strong>Tag</strong> property can be used to identify the GameObject.  Using the <strong>Tag</strong> property to search for <strong>GameObject</strong>s in the scene is more efficient than using it&#8217;s name. If you will be accessing a <strong>GameObject</strong> a lot, then it is better to assign the GameObject an identifiable <strong>Tag</strong> and use the <strong>Tag</strong> to find the <strong>GameObject</strong> instead of the <strong>Name</strong> property.</li>
<li><strong>Layer</strong>: The <strong>Layer</strong> property is used to selectively render certain objects (the <strong>Camera</strong> component&#8217;s <strong>Culling Mask</strong> property can be used to disable rendering of certain GameObjects according to their layer) or to ignore raycast (The <strong>Physics.Raycast</strong> function accepts a <strong>Layer Mask</strong> property which can be used to ignore <strong>GameObjects</strong> according to their <strong>Layer</strong> property).</li>
<li><strong>Transform</strong>: Every <strong>GameObject</strong> in the scene has one and only one <strong>Transform</strong> component. The <strong>Transform</strong> component determines the position, orientation, and scale of a <strong>GameObject</strong> relative to its parent (<strong>GameObject</strong>s at the top-level in the hierarchy view are relative to the scene&#8217;s world-origin).</li>
<li><strong>Static</strong>: If a <strong>GameObject</strong> will not move or it should be used for lightmapping, navigation, or occlusion culling (these topics will be discussed in a later article), then it&#8217;s <strong>Static</strong> property should be enabled.  Usually you will only do this on <strong>GameObject</strong>s that have a <strong>Mesh</strong> component attached to them and will never move in the scene (such as buildings, level geometry, and static environment props like rocks and trees).  Anything that can be moved (such as physics or kinematic controlled <strong>GameObjects</strong>, or animated character models) should not be marked as <strong>Static</strong>.</li>
</ul>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-GameObject.html" title="Unity - GameObject">Source</a>]</p>
<span id="Searching_for_GameObjects"><h2>Searching for GameObjects</h2></span>
<p>It may be necessary to find a particular <strong>GameObject</strong> in your scene at run-time. This is done with the power of scripting. There are several ways to accomplish this task and it is important to know the correct way of doing this depending on the situation.</p>
<p>Suppose you have the following scene:</p>
<div id="attachment_3580" class="wp-caption alignnone" style="width: 1049px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Test-Scene.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Test-Scene.png" alt="Unity - Test Scene" title="Unity - Test Scene" width="1039" height="733" class="size-full wp-image-3580" /></a><p class="wp-caption-text">Unity &#8211; Test Scene</p></div>
<p>(Click on the image to show it full-size).</p>
<p>This simple test scene consists of 3 cubes:</p>
<ul>
<li><strong>Cube 01</strong> with tag &#8220;<strong>Right</strong>&#8220;</li>
<li><strong>Cube 02</strong> with tag &#8220;<strong>Middle</strong>&#8220;</li>
<li><strong>Cube 03</strong> with tag &#8220;<strong>Left</strong>&#8220;</li>
</ul>
<p>There are 3 ways to access the cube GameObjects in this scene:</p>
<ul>
<li><strong>By Reference</strong></li>
<li><strong>By Name</strong></li>
<li><strong>By Tag</strong></li>
</ul>
<span id="Assign_by_Reference"><h3>Assign by Reference</h3></span>
<p>If a <strong>GameObject</strong> is created in the editor (as opposed to creating the object dynamically at run-time) it is possible to assign the GameObject to a script variable using the <strong>Inspector</strong> view.</p>
<p>Create a script similar to what is shown below.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="AssignByReference.js">
#pragma strict

public var otherGameObject : GameObject;

function Start () 
{
	if ( otherGameObject != null )
	{
		Debug.Log("I am \"" + name + "\" and I have a reference to the "
		  + "GameObject with name \"" + otherGameObject.name + "\"" );
	}
}
</pre>
</div>
<p>If you assign this script to the cube <strong>GameObject</strong>s in this scene (drag and drop the script from the <strong>Project</strong> view onto the <strong>GameObject</strong>s in the <strong>Hierarchy</strong> view) then you see the public property called &#8220;Other Game Object&#8221; exposed in the <strong>Inspector</strong> view (shown highlighted in the image below).</p>
<div id="attachment_3586" class="wp-caption alignnone" style="width: 326px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Assign-by-Reference.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Assign-by-Reference.png" alt="Unity - Assign by Reference" title="Unity - Assign by Reference" width="316" height="675" class="size-full wp-image-3586" /></a><p class="wp-caption-text">Unity &#8211; Assign by Reference</p></div>
<p>If you click the little circle icon <img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Select-GameObject-button.png" alt="Select Object" /> next to the parameter in the <strong>Inspector</strong> view, you will be presented with a dialog box that lets you select a compatible <strong>GameObject</strong> from the scene (make sure you select the &#8220;<strong>Scene</strong>&#8221; tab at the top of this dialog box).</p>
<div id="attachment_3587" class="wp-caption alignnone" style="width: 259px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Select-GameObject.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Select-GameObject.png" alt="Unity - Select GameObject" title="Unity - Select GameObject" width="249" height="502" class="size-full wp-image-3587" /></a><p class="wp-caption-text">Unity &#8211; Select GameObject</p></div>
<p>If I assign <strong>Cube 01</strong> a reference to <strong>Cube 02</strong>, <strong>Cube 02</strong> a reference to <strong>Cube 03</strong> and <strong>Cube 03</strong> a reference to <strong>Cube 01</strong> then I should get the following output in the console window (Shift + Ctrl + C):</p>
<div id="attachment_3592" class="wp-caption alignnone" style="width: 764px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Console-Window.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Console-Window.png" alt="Unity - Console Window" title="Unity - Console Window" width="754" height="438" class="size-full wp-image-3592" /></a><p class="wp-caption-text">Unity &#8211; Console Window</p></div>
<p>This is probably the most efficient way to assign a reference to a <strong>GameObject</strong>.  However, you may not know until run-time which <strong>GameObject</strong> you need to refer to.</p>
<span id="Find_by_Tag"><h3>Find by Tag</h3></span>
<p>You can also use a <strong>GameObject</strong>&#8216;s <strong>Tag</strong> property to find it within the scene.</p>
<p>Modify the script using the following code:</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="Script.js">
#pragma strict

public var otherTag : String;
private var otherGameObject : GameObject;

function Start () 
{
	if ( otherTag.Length > 0 )
	{
		otherGameObject = GameObject.FindGameObjectWithTag(otherTag);
		if ( otherGameObject != null )
		{
		Debug.Log("I have tag \"" + tag + "\" and I found a GameObject with tag \""
		  + otherGameObject.tag + "\"" );		
		}
	}
}
</pre>
</div>
<p>In the Inspector, change the <strong>Other Tag</strong> script property to match the <strong>Tag</strong> property that was assigned to each corresponding <strong>GameObject</strong> (For example, <strong>Cube 01</strong> has Tag &#8220;<strong>Right</strong>&#8220;).</p>
<p>If you run the game, you should see the following output in the <strong>Console</strong> window (Shift + Ctrl + C):</p>
<div id="attachment_3595" class="wp-caption alignnone" style="width: 764px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Console-Window-2.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Console-Window-2.png" alt="Unity - Console Window (2)" title="Unity - Console Window (2)" width="754" height="438" class="size-full wp-image-3595" /></a><p class="wp-caption-text">Unity &#8211; Console Window (2)</p></div>
<p>Using the <strong>Tag</strong> property to find a <strong>GameObject</strong> in the scene is more efficient than using the <strong>Name</strong> property because Unity is able to pre-sort <strong>GameObject</strong>s in the scene into lists according to the <strong>GameObject</strong>&#8216;s <strong>Tag</strong> property.</p>
<p>The <strong>Tag</strong> property does not have to be unique. For example, many <strong>GameObject</strong>s can have the same <strong>Tag</strong> and you can retrieve all the <strong>GameObject</strong>s in the scene with a particular <strong>Tag</strong> value using the <strong>GameObject.FindGameObjectsWithTag(String)</strong> static method (notice the plural ending on <strong>GameObjects</strong> in the method name &#8220;<strong>FindGameObjectsWithTag</strong>&#8220;).</p>
<p>The <strong>GameObject.FindGameObjectWithTag(String tag)</strong> static method is used to retrieve a reference to a single <strong>GameObject</strong> and the <strong>GameObject.FindGameObjectsWithTag(String tag)</strong> static method is used to retrieve an array of all <strong>GameObjects</strong> with the matching tag.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/ScriptReference/GameObject.FindWithTag.html" title="GameObject.FindWithTag (FindGameObjectWithTag)" target="_blank">Source</a>]</p>
<span id="Find_by_Name"><h3>Find by Name</h3></span>
<p><strong>GameObject</strong>s can also be searched in the scene by their assigned name using the <strong>GameObject.Find(String name)</strong> static method.  This is probably the most inefficient way to search for <strong>GameObject</strong>&#8216;s because Unity must search every <strong>GameObject</strong> in the scene matching it&#8217;s name property to the search parameter.  In some cases, it may be unavoidable. For example, a dynamically created object that does not have a tag can only be found by it&#8217;s name.</p>
<p>Generally, you do not want to call this method every frame (in the <strong>Update</strong> method) but instead you will want to cache a reference to the <strong>GameObject</strong> and only search for it by name if the reference is NULL.</p>
<p>I will not show an example of this as it is very similar to the example I already showed using the <strong>Tag</strong> property.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/ScriptReference/GameObject.Find.html" title="GameObject.Find" target="_blank">Source</a>]</p>
<span id="Prefabs"><h1>Prefabs</h1></span>
<p>A <strong>Prefab</strong> is a <strong>GameObject</strong> that you can save to your <strong>Asset</strong> folder so that you can easily create copies of that <strong>GameObject</strong> in your scene or in other scenes.  <strong>Prefabs</strong> can also be instantiated dynamically at run-time using scripts.</p>
<p>A <strong>Prefab</strong> can also be considered a <strong>Template</strong> for a complex <strong>GameObject</strong> structure.  You can modify the properties of the individual instances so that each instance of the <strong>Perfab</strong> can have different properties while maintaining the general structure of the original <strong>Perfab</strong>.</p>
<p>To create a <strong>Prefab</strong>, first construct your <strong>GameObject</strong> in the scene view then drag-and-drop the <strong>GameObject</strong> from the <strong>Hierarchy</strong> view to the <strong>Project</strong> view.</p>
<span id="Creating_Prefabs"><h2>Creating Prefabs</h2></span>
<p>Let&#8217;s create a <strong>Brick</strong> prefab that can be used to instantiate a lot of <strong>Brick</strong> instances in the scene at runtime.</p>
<p>Open Unity and create a new scene.</p>
<p>Create a <strong>Cube GameObject</strong> (select <strong>GameObject -> Create Other -> Cube</strong> from the main menu).  Rename the <strong>Cube GameObject</strong> to &#8220;<strong>Brick</strong>&#8220;.</p>
<div id="attachment_3821" class="wp-caption alignnone" style="width: 1034px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Brick-Prefab.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Brick-Prefab.png" alt="Unity - Brick Prefab" title="Unity - Brick Prefab" width="1024" height="638" class="size-full wp-image-3821" /></a><p class="wp-caption-text">Unity &#8211; Brick Prefab</p></div>
<p>Add a Rigidbody component to the <strong>Brick GameObject</strong> (with the <strong>Brick</strong> selected, select <strong>Component -> Physics -> Rigidbody</strong> from the main menu).  Now we have a physics controlled brick.</p>
<p>Now drag-and-drop the <strong>Brick</strong> game object from the <strong>Hierarchy</strong> view into the <strong>Project</strong> view.  You have just created a <strong>Prefab</strong>!</p>
<div id="attachment_3822" class="wp-caption alignnone" style="width: 1016px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Brick-Prefab-2.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Brick-Prefab-2.png" alt="Unity - Brick Prefab (2)" title="Unity - Brick Prefab (2)" width="1006" height="744" class="size-full wp-image-3822" /></a><p class="wp-caption-text">Unity &#8211; Brick Prefab (2)</p></div>
<p>In the screen shot above, you see in the <strong>Project</strong> view that we have created a new <strong>Asset</strong> called <strong>Brick</strong>. The <strong>Asset</strong> is a copy of the original <strong>Brick GameObject</strong> in the <strong>Hierarchy</strong> view.  You will also notice that the <strong>Brick GameObject</strong> in the <strong>Hierarchy</strong> view is colored <strong>blue</strong>.  This indicates that the <strong>GameObject</strong> is created from a <strong>Prefab</strong> Asset.</p>
<span id="Components"><h1>Components</h1></span>
<p><strong>Components</strong> give <strong>GameObjects</strong> their functionality.  A <strong>GameObject</strong> can be considered a container for many different <strong>Components</strong>.</p>
<p>When you create an empty <strong>GameObject</strong>, it will always have the <strong>Transform</strong> component by default. A <strong>GameObject</strong> cannot exist without a <strong>Transform</strong> component because this component determines the <strong>GameObject</strong>&#8216;s position, orientation, and scale in the world.  You cannot remove the <strong>Transform</strong> component from a <strong>GameObject</strong>.</p>
<p><strong>Components</strong> can be added to a <strong>GameObject</strong> by selecting the <strong>GameObject</strong> in either the <strong>Hierarchy</strong> or the <strong>Scene</strong> view. With a <strong>GameObject</strong> selected, choose the <strong>Component</strong> you want to add to the <strong>GameObject</strong> using the <strong>Component</strong> menu item on the main menu.</p>
<p>For the remainder of this article, I will provide a brief introduction to the different types of components that the Unity editor provides.  In later articles I will demonstrate how to use these components in more detail.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/Components.html" title="Unity - Components" target="_blank">Source</a>]</p>
<span id="Animation_Components"><h2>Animation Components</h2></span>
<p>The animation components allow you to import or create animation data that can be used to manipulate <strong>GameObjects</strong> at run-time.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/comp-AnimationGroup.html" title="Unity - Animation Components" target="_blank">Source</a>]</p>
<span id="Animation"><h3>Animation</h3></span>
<p>The <strong>Animation</strong> component allows you to assign a list of animations that can be played using the animation scripting interface.</p>
<div id="attachment_3621" class="wp-caption alignnone" style="width: 329px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Animation-Component.gif"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Animation-Component.gif" alt="Unity - Animation Component" title="Unity - Animation Component" width="319" height="663" class="size-full wp-image-3621" /></a><p class="wp-caption-text">Unity &#8211; Animation Component</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Animation.html" title="Unity - Animation" target="_blank">Source</a>]</p>
<span id="Animation_Clip"><h3>Animation Clip</h3></span>
<p>The <strong>Animation Clip</strong> is an asset component that is added to the Animation component discussed above.  The Animation Clip contains the animation data.  Animation Clips that are imported from an animated mesh file (such as FBX file) cannot be manipulated directly. You must either create a new Animation Clip asset in the project or duplicate (Ctrl-D) an Animation Clip that has been imported.</p>
<p>Animation Clips can be edited using the <strong>Animation View</strong> shown below.</p>
<div id="attachment_3623" class="wp-caption alignnone" style="width: 892px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Animation-View-2.gif"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Animation-View-2.gif" alt="Unity - Animation View" title="Unity - Animation View" width="882" height="588" class="size-full wp-image-3623" /></a><p class="wp-caption-text">Unity &#8211; Animation View</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-AnimationClip.html" title="Unity - Animation Clip" target="_blank">Source</a>]</p>
<span id="Audio_Components"><h2>Audio Components</h2></span>
<p>The Audio components implement both ambient (music) and one-shot sound effects in Unity.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/comp-AudioGroup.html" title="Unity - Audio Components" target="_blank">Source</a>]</p>
<span id="Audio_Listener"><h3>Audio Listener</h3></span>
<p>The <strong>Audio Listener</strong> is usually attached to the <strong>Main Camera</strong> GameObject. This component will determine how the 3D sound effects are produced.</p>
<p>The <strong>Audio Listener</strong> component does not have any properties to manipulate.</p>
<div id="attachment_3628" class="wp-caption alignnone" style="width: 353px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Audio-Listener.gif"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Audio-Listener.gif" alt="Unity - Audio Listener" title="Unity - Audio Listener" width="343" height="237" class="size-full wp-image-3628" /></a><p class="wp-caption-text">Unity &#8211; Audio Listener</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-AudioListener.html" title="Unity - Audio Listener" target="_blank">Source</a>]</p>
<span id="Audio_Source"><h3>Audio Source</h3></span>
<p>An <strong>Audio Source</strong> component is used to produce sound effects in the game.  Audio sources can be attached to any GameObject.  The position of the GameObject in the world will determine the position and attenuation of the <strong>Audio Source</strong>.</p>
<div id="attachment_3630" class="wp-caption alignnone" style="width: 353px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Audio-Source.gif"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Audio-Source.gif" alt="Unity - Audio Source" title="Unity - Audio Source" width="343" height="791" class="size-full wp-image-3630" /></a><p class="wp-caption-text">Unity &#8211; Audio Source</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-AudioSource.html" title="Unity - Audio Source" target="_blank">Source</a>]</p>
<span id="Effects_Components"><h2>Effects Components</h2></span>
<p>Effects Components all you to add visual effects to the game.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/comp-Effects.html" title="Unity - Effects" target="_blank">Source</a>]</p>
<span id="Particle_System_Shuriken"><h3>Particle System (Shuriken)</h3></span>
<p>Unity 3.5 introduced a new particle system called Shuriken.  Shuriken is a powerful particle effects editor that allows you to easily create complex particle effects.</p>
<p>The Particle System component is manipulated with the Particle Effects view.</p>
<div id="attachment_3666" class="wp-caption alignnone" style="width: 943px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Particle-System.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Particle-System.png" alt="Unity - Particle System (Shuriken)" title="Unity - Particle System (Shuriken)" width="933" height="510" class="size-full wp-image-3666" /></a><p class="wp-caption-text">Unity &#8211; Particle System (Shuriken)</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-ParticleSystem.html" title="Unity - Particle System (Shuriken)" target="_blank">Source</a>]</p>
<span id="Halo"><h3>Halo</h3></span>
<p>The <strong>Halo</strong> Component can be used to render a circular particle at the position of the GameObject.  The Halo component is used to simulate a glow and works best when used on point light sources.</p>
<div id="attachment_3634" class="wp-caption alignnone" style="width: 667px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Halo-Component.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Halo-Component.png" alt="Unity - Halo Component" title="Unity - Halo Component" width="657" height="470" class="size-full wp-image-3634" /></a><p class="wp-caption-text">Unity &#8211; Halo Component</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Halo.html" title="Unity - Halo" target="_blank">Source</a>]</p>
<span id="Lens_Flare"><h3>Lens Flare</h3></span>
<p>The <strong>Lens Flare</strong> component is normally attached to light sources and simulates an effect that is typical on camera lenses when a very bright light source is in direct view of the camera.</p>
<div id="attachment_3638" class="wp-caption alignnone" style="width: 667px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Lens-Flare-Component.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Lens-Flare-Component.png" alt="Unity - Lens Flare Component" title="Unity - Lens Flare Component" width="657" height="470" class="size-full wp-image-3638" /></a><p class="wp-caption-text">Unity &#8211; Lens Flare Component</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-LensFlare.html" title="Unity - Lens Flare" target="_blank">Source</a>]</p>
<span id="Line_Renderer"><h3>Line Renderer</h3></span>
<p>The <strong>Line Renderer</strong> component is used to render 3D textured path of polygons using an array of points to determine the path.  The path is not smoothed or interpolated so to create smooth paths, you will need alot of points.</p>
<p>The <strong>Line Renderer</strong> component does not fade-out over time.</p>
<div id="attachment_3640" class="wp-caption alignnone" style="width: 663px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Line-Renderer-Component.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Line-Renderer-Component.png" alt="Unity - Line Renderer Component" title="Unity - Line Renderer Component" width="653" height="545" class="size-full wp-image-3640" /></a><p class="wp-caption-text">Unity &#8211; Line Renderer Component</p></div>
<p>The <strong>Line Renderer</strong> component uses the same algorithm to compute the geometry of the line as the <strong>Trail Renderer</strong> component discussed next.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-LineRenderer.html" title="Unity - Line Renderer" target="_blank">Source</a>]</p>
<span id="Trail_Renderer"><h3>Trail Renderer</h3></span>
<p>Like the <strong>Line Renderer</strong> component, the <strong>Trail Renderer</strong> component will draw a 3D line using the line drawing algorithm the <strong>Line Renderer</strong> uses.  Unlike the <strong>Line Renderer</strong> component, the <strong>Trail Renderer</strong> component will use the last sampled position  of the <strong>GameObject</strong> it is attached to determine the path of the line.  This means that the <strong>GameObject</strong> must be moving for a trail to be formed.  Stationary <strong>GameObjects</strong> will not produce a trail.</p>
<div id="attachment_3641" class="wp-caption alignnone" style="width: 903px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Trail-Renderer.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Trail-Renderer.png" alt="Unity - Trail Renderer" title="Unity - Trail Renderer" width="893" height="607" class="size-full wp-image-3641" /></a><p class="wp-caption-text">Unity &#8211; Trail Renderer</p></div>
<p>The <strong>Trail Renderer</strong> component will automatically fade-out over time determined by the <strong>Time</strong> parameter of the <strong>Trail Renderer</strong> component.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-TrailRenderer.html" title="Unity - Trail Renderer" target="_blank">Source</a>]</p>
<span id="Projector"><h3>Projector</h3></span>
<p>A Projector component is similar to the Camera component in that it defines a view frustum. Any geometry that is within the view frustrum will have the the projector&#8217;s material projected onto it.  Projectors are very useful for things like bullet holes in walls or shadow blobs below characters and vehicles which is a cheap way of producing dynamic shadows!</p>
<p>Do not use projects where a normal textured quad will produce the same result!</p>
<div id="attachment_3644" class="wp-caption alignnone" style="width: 762px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Projector-Component.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Projector-Component.png" alt="Unity - Projector Component" title="Unity - Projector Component" width="752" height="623" class="size-full wp-image-3644" /></a><p class="wp-caption-text">Unity &#8211; Projector Component</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Projector.html" title="Unity - Projector" target="_blank">Source</a>]</p>
<span id="Mesh_Components"><h2>Mesh Components</h2></span>
<p>Meshes are the primary graphics primitive used to represent visual objects in Unity.  Several components exist to produce static or animated characters, and 3D text.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/comp-MeshGroup.html" title="Unity - Mesh Components" target="_blank">Source</a>]</p>
<span id="Mesh_Filter"><h3>Mesh Filter</h3></span>
<p>The <strong>Mesh Filter</strong> component is a container for mesh data.  When you import a model into your project (an FBX file for example) it is possible that the model contains several sub-meshes.  The <strong>Mesh Filter</strong> component is used to refer to a particular sub-mesh of the model.</p>
<p>A <strong>Mesh Filter</strong> component must be used together with a <strong>Mesh Renderer</strong> component on the same <strong>GameObject</strong>.  A <strong>GameObject</strong> with a <strong>Mesh Filter</strong> component will store the referenced mesh geometry in garphics memory but nothing will be rendered without a <strong>Mesh Renderer</strong> component assigned to the <strong>GameObject</strong>.</p>
<div id="attachment_3646" class="wp-caption alignnone" style="width: 624px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Mesh-Filter.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Mesh-Filter.png" alt="Unity - Mesh Filter" title="Unity - Mesh Filter" width="614" height="403" class="size-full wp-image-3646" /></a><p class="wp-caption-text">Unity &#8211; Mesh Filter</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-MeshFilter.html" title="Unity - Mesh Filter" target="_blank">Source</a>]</p>
<span id="Mesh_Renderer"><h3>Mesh Renderer</h3></span>
<p>A <strong>Mesh Renderer</strong> component will take the geometry data from the <strong>Mesh Filter</strong> component and render it to the screen at the GameObject&#8217;s current position and orientation.</p>
<div id="attachment_3647" class="wp-caption alignnone" style="width: 624px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Mesh-Renderer.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Mesh-Renderer.png" alt="Unity - Mesh Renderer" title="Unity - Mesh Renderer" width="614" height="403" class="size-full wp-image-3647" /></a><p class="wp-caption-text">Unity &#8211; Mesh Renderer</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-MeshRenderer.html" title="Unity - Mesh Renderer" target="_blank">Source</a>]</p>
<span id="Skinned_Mesh_Renderer"><h3>Skinned Mesh Renderer</h3></span>
<p>The <strong>Skinned Mesh Renderer</strong> component is used to render animated skinned meshes (like character models).</p>
<div id="attachment_3649" class="wp-caption alignnone" style="width: 815px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Skinned-Mesh-Renderer.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Skinned-Mesh-Renderer.png" alt="Unity - Skinned Mesh Renderer" title="Unity - Skinned Mesh Renderer" width="805" height="541" class="size-full wp-image-3649" /></a><p class="wp-caption-text">Unity &#8211; Skinned Mesh Renderer</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-SkinnedMeshRenderer.html" title="Unity - Skinned Mesh Renderer" target="_blank">Source</a>]</p>
<span id="Text_Mesh"><h3>Text Mesh</h3></span>
<p>The <strong>Text Mesh</strong> component is used in conjunction with the <strong>Mesh Renderer</strong> to produce 3D text in the scene.  The text is not extruded but instead 2D quads are used to render each letter in 3D space.  This means that the text will not be visible when viewed from the side.  This component could be used to create dynamic billboard text (for example a scrolling marquee light board sign)</p>
<div id="attachment_3651" class="wp-caption alignnone" style="width: 751px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Text-Mesh.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Text-Mesh.png" alt="Unity - Text Mesh" title="Unity - Text Mesh" width="741" height="571" class="size-full wp-image-3651" /></a><p class="wp-caption-text">Unity &#8211; Text Mesh</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-TextMesh.html" title="Unity - Text Mesh" target="_blank">Source</a>]</p>
<span id="Rendering_Components"><h2>Rendering Components</h2></span>
<p>Render components are components that have something to do with rendering in-game and user interface elements.  This category includes the camera, gui elements, lights, occlusion, skybox and Level of Detail components.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/comp-RenderingGroup.html" title="Unity - Rendering Components" target="_blank">Source</a>]</p>
<span id="Camera"><h3>Camera</h3></span>
<p>The <strong>Camera</strong> component is the most ubiquitous component in your scene. Without at least one <strong>GameObject</strong> with a <strong>Camera</strong> component in your scene, you will not see anything in your game.  Playing the game without a camera in the scene will produce a black screen.</p>
<div id="attachment_3656" class="wp-caption alignnone" style="width: 705px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Camera-Component.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Camera-Component.png" alt="Unity - Camera Component" title="Unity - Camera Component" width="695" height="543" class="size-full wp-image-3656" /></a><p class="wp-caption-text">Unity &#8211; Camera Component</p></div>
<p>When you select the <strong>Camera</strong>, the <strong>Camera Preview</strong> dialog appears in your scene view.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Camera.html" title="Unity - Camera" target="_blank">Source</a>]</p>
<span id="Flare_Layer"><h3>Flare Layer</h3></span>
<p>A <strong>Flare Layer</strong> component must be added to the <strong>Camera</strong> in order for the <strong>Lens Flare</strong> component to render.  </p>
<div id="attachment_3657" class="wp-caption alignnone" style="width: 679px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Flare-Layer.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Flare-Layer.png" alt="Unity - Flare Layer" title="Unity - Flare Layer" width="669" height="541" class="size-full wp-image-3657" /></a><p class="wp-caption-text">Unity &#8211; Flare Layer</p></div>
<p>If you remove the <strong>Flare Layer</strong> component from the <strong>Camera</strong> or disable the component, the <strong>Lens Flare</strong> effect will still render in the <strong>Scene</strong> view but it will not appear in the <strong>Game</strong> view.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-FlareLayer.html" title="Unity - Flare Layer" target="_blank">Source</a>]</p>
<span id="GUI_Layer"><h3>GUI Layer</h3></span>
<p>Like the <strong>Flare Layer</strong>, the <strong>GUI Layer</strong> is required to render all 2D <strong>GUI Text</strong> and <strong>GUI Texture</strong> elements.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-GUILayer.html" title="Unity - GUI Layer" target="_blank">Source</a>]</p>
<span id="GUI_Text"><h3>GUI Text</h3></span>
<p>The <strong>GUI Text</strong> component is used to display text on the screen.  The position the text appears on screen is determined by the <strong>GameObject</strong>&#8216;s X and Y position values.  The X and Y values are in normalized (in the range [0,1]) screen space where (0,0) is the bottom-left and (1,1) is the top-right point on the screen.</p>
<div id="attachment_3659" class="wp-caption alignnone" style="width: 1073px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-GUI-Text.gif"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-GUI-Text.gif" alt="Unity - GUI Text" title="Unity - GUI Text" width="1063" height="711" class="size-full wp-image-3659" /></a><p class="wp-caption-text">Unity &#8211; GUI Text</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-GuiText.html" title="Unity - GUI Text" target="_blank">Source</a>]</p>
<span id="GUI_Texture"><h3>GUI Texture</h3></span>
<p>The <strong>GUI Texture</strong> component is used to display a 2D screen texture elements.  The <strong>GUI Texture</strong> component use&#8217;s the <strong>GameObject</strong>&#8216;s X and Y position to determine the normalized (in the range [0,1]) screen space of where the texture will appear.</p>
<div id="attachment_3661" class="wp-caption alignnone" style="width: 863px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-GUI-Texture.gif"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-GUI-Texture.gif" alt="Unity - GUI Texture" title="Unity - GUI Texture" width="853" height="523" class="size-full wp-image-3661" /></a><p class="wp-caption-text">Unity &#8211; GUI Texture</p></div>
<p>As you can see from the image above, the position of the <strong>GameObject</strong> with the <strong>GUI Texture</strong> component is (0.5, 0.5, 0) which causes the <strong>GUI Texture</strong> to appear in the center of the screen.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-GuiTexture.html" title="Unity - GUI Texture" target="_blank">Source</a>]</p>
<span id="Light"><h3>Light</h3></span>
<p>Lights are used to illuminate the scene.</p>
<div id="attachment_3668" class="wp-caption alignnone" style="width: 905px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Light-Component.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Light-Component.png" alt="Unity - Light Component" title="Unity - Light Component" width="895" height="479" class="size-full wp-image-3668" /></a><p class="wp-caption-text">Unity &#8211; Light Component</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Light.html" title="Unity - Light" target="_blank">Source</a>]</p>
<span id="Light_Probe_Group"><h3>Light Probe Group</h3></span>
<p>The <strong>Light Probe Group</strong> component allows you to add light probes to the scene.  A <strong>Light Probe</strong> works in conjunction with <strong>Light Mapping</strong> (I will discuss Light Mapping in another article) in order to properly illuminate dynamic objects according to the light contributions of baked-only lights.</p>
<div id="attachment_3671" class="wp-caption alignnone" style="width: 951px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Light-Probes.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Light-Probes.png" alt="Unity - Light Probes" title="Unity - Light Probes" width="941" height="731" class="size-full wp-image-3671" /></a><p class="wp-caption-text">Unity &#8211; Light Probes</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-LightProbeGroup.html" title="Unity - Light Probe Group" target="_blank">Source</a>]</p>
<span id="Occlusion_Area_Pro_Only"><h3>Occlusion Area (Pro Only)</h3></span>
<p>The <strong>Occlusion Area</strong> component is used to define a region in the game where occlusion culling will occur.</p>
<p>By default, Unity will generate occlusion data based on the bounds of the objects in the scene but you may want to specify certain areas that will generate data structures for occluding static objects (view volume) and dynamic objects (target volume).  The <strong>Occlusion Area</strong> component allows you to do that.</p>
<div id="attachment_3675" class="wp-caption alignnone" style="width: 893px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Occlusion-Area.gif"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Occlusion-Area.gif" alt="Unity - Occlusion Area" title="Unity - Occlusion Area" width="883" height="479" class="size-full wp-image-3675" /></a><p class="wp-caption-text">Unity &#8211; Occlusion Area</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-OcclusionArea.html" title="Unity - Occlusion Area" target="_blank">Source</a>]</p>
<span id="Occlusion_Portals"><h3>Occlusion Portals</h3></span>
<p>The <strong>Occlusion Portal</strong> component is similar to <strong>Occlusion Area</strong> component in that it allows you to define a 3 dimensional area that is used for occlusion culling.</p>
<p>An Occlusion Portal is used in doorways where the door can be opened and closed.  The portal can be &#8220;Opened&#8221; or &#8220;Closed&#8221; in script when the door that is occluding the geometry is opened or closed.</p>
<div id="attachment_3676" class="wp-caption alignnone" style="width: 1039px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Occlusion-Portal.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Occlusion-Portal.png" alt="Unity - Occlusion Portal" title="Unity - Occlusion Portal" width="1029" height="483" class="size-full wp-image-3676" /></a><p class="wp-caption-text">Unity &#8211; Occlusion Portal</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-OcclusionPortal.html" title="Unity - Occlusion Portals" target="_blank">Source</a>]</p>
<span id="Skybox"><h3>Skybox</h3></span>
<p>A <strong>Skybox</strong> component is used to simulate an environment that wraps around your entire game world.  You can either add the Skybox component to the main camera, or if you have many camera&#8217;s in the scene and you want all of them to use the same Skybox, you can configure the Skybox material in the Render Settings (Choose <strong>Edit -> Render Settings</strong> from the main menu).</p>
<div id="attachment_3678" class="wp-caption alignnone" style="width: 749px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Skybox.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Skybox.png" alt="Unity - Skybox" title="Unity - Skybox" width="739" height="413" class="size-full wp-image-3678" /></a><p class="wp-caption-text">Unity &#8211; Skybox</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Skybox.html" title="Unity - Skybox" target="_blank">Source</a>]</p>
<span id="Level_of_Detail_Pro_Only"><h3>Level of Detail (Pro Only)</h3></span>
<p>The LOD Group component allows you to specify different representations of an object based on it&#8217;s distance away from the camera.</p>
<div id="attachment_3679" class="wp-caption alignnone" style="width: 1091px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-LOD-Group.gif"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-LOD-Group.gif" alt="Unity - LOD Group" title="Unity - LOD Group" width="1081" height="553" class="size-full wp-image-3679" /></a><p class="wp-caption-text">Unity &#8211; LOD Group</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-LODGroup.html" title="Unity  - Level of Detail" target="_blank">Source</a>]</p>
<span id="Physics_Components"><h2>Physics Components</h2></span>
<p>Unity uses the <strong>NVIDIA PhysX</strong> physics engine to perform the physics simulations.  The physics components are required for GameObjects to participate in physics simulations and to perform collision detection with other physics controlled GameObjects.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/comp-DynamicsGroup.html" title="Unity - Physics Components" target="_blank">Source</a>]</p>
<span id="Physics"><h3>Physics</h3></span>
<span id="Rigidbody"><h4>Rigidbody</h4></span>
<p>The <strong>Rigidbody</strong> component allows the <strong>GameObjects</strong> to be influenced by physical forces such as gravity or wind forces.</p>
<p>Static objects that will not be physics simulated do not need to have rigid bodies assigned to them.</p>
<div id="attachment_3681" class="wp-caption alignnone" style="width: 735px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Rigidbody.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Rigidbody.png" alt="Unity - Rigidbody" title="Unity - Rigidbody" width="725" height="365" class="size-full wp-image-3681" /></a><p class="wp-caption-text">Unity &#8211; Rigidbody</p></div>
<p> In the image above, you see three cubes hovering over a plane.  When simulating, the cubes will fall onto the plane.  The cubes will act under the force of gravity and therefor must have a <strong>Rigidbody</strong> component assigned to them.  The plane however is stationary and won&#8217;t move. In this case, the plane does not need to have a <strong>Rigidbody</strong> component assigned to it.</p>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-Rigidbody.html" title="Unity - Rigid Body" target="_blank">Source</a>]</p>
<span id="Character_Controller"><h4>Character Controller</h4></span>
<p>The <strong>Character Controller</strong> component is usually attached to the player character and any game character that needs to move around the scene.  This component will create a <strong>Capsule Collider</strong> around the character that is used to perform the physics collision with the environment.</p>
<div id="attachment_3683" class="wp-caption alignnone" style="width: 703px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Character-Controller.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Character-Controller.png" alt="Unity - Character Controller" title="Unity - Character Controller" width="693" height="557" class="size-full wp-image-3683" /></a><p class="wp-caption-text">Unity &#8211; Character Controller</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-CharacterController.html" title="Unity - Character Controller" target="_blank">Source</a>]</p>
<span id="Consant_Force"><h4>Consant Force</h4></span>
<p>The <strong>Constant Force</strong> component can be used to apply a physical force to a GameObject.  This will allow the GameObject to appear to be pushed through space by an external force (such as a rocket).</p>
<div id="attachment_3685" class="wp-caption alignnone" style="width: 768px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Constant-Force.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Constant-Force.png" alt="Unity - Constant Force" title="Unity - Constant Force" width="758" height="477" class="size-full wp-image-3685" /></a><p class="wp-caption-text">Unity &#8211; Constant Force</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-ConstantForce.html" title="Unity - Constant Force" target="_blank">Source</a>]</p>
<span id="Colliders"><h3>Colliders</h3></span>
<p>Collider components allow for collision detection to occur.  Without a collider component on the <strong>GameObject</strong>, then it will simply pass through all other objects as if they were not there.</p>
<span id="Sphere_Collider"><h4>Sphere Collider</h4></span>
<p>As the name suggests, a <strong>Sphere Collider</strong> component simulates the shape of a sphere. This collider is commonly used on sphere shaped objects.</p>
<div id="attachment_3689" class="wp-caption alignnone" style="width: 699px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Sphere-Collider.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Sphere-Collider.png" alt="Unity - Sphere Collider" title="Unity - Sphere Collider" width="689" height="399" class="size-full wp-image-3689" /></a><p class="wp-caption-text">Unity &#8211; Sphere Collider</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-SphereCollider.html" title="Unity - Sphere Collider" target="_blank">Source</a>]</p>
<span id="Box_Collider"><h4>Box Collider</h4></span>
<p>The <strong>Box Collider</strong> component should be placed on objects that resemble the shape of a box.</p>
<div id="attachment_3691" class="wp-caption alignnone" style="width: 699px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Box-Collider.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Box-Collider.png" alt="Unity - Box Collider" title="Unity - Box Collider" width="689" height="399" class="size-full wp-image-3691" /></a><p class="wp-caption-text">Unity &#8211; Box Collider</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-BoxCollider.html" title="Unity - Box Collider" target="_blank">Source</a>]</p>
<span id="Capsule_Collider"><h4>Capsule Collider</h4></span>
<p>The <strong>Capsule Collider</strong> component is used on cylinder shaped objects that are rounded on each end.  A <strong>Capsule Collider</strong> is automatically created on <strong>GameObjects</strong> that have a <strong>Character Controller</strong> component attached to them.</p>
<div id="attachment_3692" class="wp-caption alignnone" style="width: 745px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Capsule-Collider.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Capsule-Collider.png" alt="Unity - Capsule Collider" title="Unity - Capsule Collider" width="735" height="361" class="size-full wp-image-3692" /></a><p class="wp-caption-text">Unity &#8211; Capsule Collider</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-CapsuleCollider.html" title="Unity - Capsule Collider" target="_blank">Source</a>]</p>
<span id="Mesh_Collider"><h4>Mesh Collider</h4></span>
<p>The <strong>Mesh Collider</strong> can be used if none of the other colliders fit the shape of your object.</p>
<p>The <strong>Mesh Collider</strong> component will not collide with other <strong>Mesh Collider</strong> components unless the &#8220;<strong>Convex</strong>&#8221; option is enabled.</p>
<div id="attachment_3694" class="wp-caption alignnone" style="width: 745px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Mesh-Collider.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Mesh-Collider.png" alt="Unity - Mesh Collider" title="Unity - Mesh Collider" width="735" height="361" class="size-full wp-image-3694" /></a><p class="wp-caption-text">Unity &#8211; Mesh Collider</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-MeshCollider.html" title="Unity - Mesh Collider" target="_blank">Source</a>]</p>
<span id="Wheel_Collider"><h4>Wheel Collider</h4></span>
<p>The Wheel Collider components are special collision components that are used for grounded vehicles.</p>
<div id="attachment_3695" class="wp-caption alignnone" style="width: 1091px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Wheel-Collider.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Wheel-Collider.png" alt="Unity - Wheel Collider" title="Unity - Wheel Collider" width="1081" height="635" class="size-full wp-image-3695" /></a><p class="wp-caption-text">Unity &#8211; Wheel Collider</p></div>
<p>[<a href="http://docs.unity3d.com/Documentation/Components/class-WheelCollider.html" title="Unity - Wheel Collider" target="_blank">Source</a>]</p>
<span id="Conclusion"><h1>Conclusion</h1></span>
<p>In this article I talked about the three basic building blocks that Unity uses to help you make games:</p>
<ul>
<li>Assets</li>
<li>GameObjects</li>
<li>Components</li>
</ul>
<p>In this article, I did not describe every component available to you in Unity but I only wanted to give a brief introduction to some of the more commonly used components that you will very likely use in your own projects.</p>
<p>In later articles, I would like to describe some of the more interesting features of the Unity editor such as terrains, physics, GUI interfaces, and special effects.</p>
<span id="Exercise"><h1>Exercise</h1></span>
<p>The intention of this exercise is to introduce you to the Asset pipeline in Unity.</p>
<ol>
<li>Create a new Unity Project (do not add any standard assets).  By default, Unity will create an empty scene with only a <strong>Main Camera</strong>.</li>
<li>Download a 3D model file or use a 3D model that you have previously created.  The  model file must be in a format that is supported by Unity (any of the model formats listed in this article will work as long as you have the relevant software installed.  FBX and OBJ model formats will work without any additional software installed). You can find free models on TurboSquid (<a href="http://www.turbosquid.com/Search/3D-Models?max_price=0&#038;&#038;min_price=0" title="Free Models on TurboSquid" target="_blank">http://www.turbosquid.com/Search/3D-Models?max_price=0&#038;&#038;min_price=0</a> &#8211; Requires you to login using a user account).</li>
<li>Save the 3D model in the Asset folder or use the <strong>Assets -> Import New Asset&#8230;</strong> command from the main menu to import your model asset into Unity.</li>
<li>Create an instance of the model you just imported in an empty scene by drag-and-droping the 3D model Asset into the scene view.</li>
<li>Create a <strong>Plane GameObject</strong> in your scene (select <strong>GameObject -> Create Other -> Plane</strong> from the main menu).</li>
<li>Zero the <strong>Position</strong> and <strong>Rotation</strong> of the <strong>Plane GameObject</strong> so that it is centered at the origin of the world.</li>
<li>Create a <strong>Cube GameObject</strong> in your scene (select <strong>GameObject -> Create Other -> Cube</strong> from the main menu).</li>
<li>Create a <strong>Sphere GameObject</strong> in your scene (select <strong>GameObject -> Create Other -> Sphere</strong> from the main menu).</li>
<li>Create a <strong>Cylinder GameObject</strong> in your scene (select <strong>GameObject -> Create Other -> Cylinder</strong> from the main menu).</li>
<li>Position the <strong>Cube</strong>,  <strong>Sphere</strong>, and <strong>Cylinder</strong> above the <strong>Plane</strong> so that no <strong>GameObjects</strong> are intersecting.</li>
<li>Import 4 different image files into your project.</li>
<li>Place a different texture on each of the 4 GameObjects you just created (<strong>Plane</strong>, <strong>Cube</strong>, <strong>Sphere</strong>, and <strong>Cylinder</strong>)</li>
<li>Create a directional light to illuminate your scene.</li>
<li>Orient your Main Camera so that all of the objects are in view.</li>
<li>Save your scene.</li>
</ol>
<p>If you play your game, you should see something similar to what is shown below.</p>
<div id="attachment_3824" class="wp-caption alignnone" style="width: 825px"><a href="http://3dgep.com/wp-content/uploads/2012/08/Unity-Asset-Pipeline-Exercise.png"><img src="http://3dgep.com/wp-content/uploads/2012/08/Unity-Asset-Pipeline-Exercise.png" alt="Unity - Asset Pipeline Exercise" title="Unity - Asset Pipeline Exercise" width="815" height="555" class="size-full wp-image-3824" /></a><p class="wp-caption-text">Unity &#8211; Asset Pipeline Exercise</p></div>
<p>Of course your scene will look better than mine. My scene is victim to &#8220;programmer art&#8221;.</p>
<span id="References"><h1>References</h1></span>
<p>The Unity User Manual:<br />
<a href="http://docs.unity3d.com/Documentation/Manual/index.html" title="Unity User Manual" target="_blank">http://docs.unity3d.com/Documentation/Manual/index.html</a></p>
<p>The Unity Component Reference documentation:<br />
<a href="http://docs.unity3d.com/Documentation/Components/index.html" title="Unity Component Reference" target="_blank">http://docs.unity3d.com/Documentation/Components/index.html</a></p>
<p>The Unity Scripting Reference:<br />
<a href="http://docs.unity3d.com/Documentation/ScriptReference/index.html" title="Unity Scripting Reference" target="_blank">http://docs.unity3d.com/Documentation/ScriptReference/index.html</a></p>
]]></content:encoded>
			<wfw:commentRss>http://3dgep.com/?feed=rss2&#038;p=3477</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Introduction to Unity 3.5</title>
		<link>http://3dgep.com/?p=3246</link>
		<comments>http://3dgep.com/?p=3246#comments</comments>
		<pubDate>Mon, 16 Jul 2012 20:24:40 +0000</pubDate>
		<dc:creator>Jeremiah van Oosten</dc:creator>
				<category><![CDATA[Unity]]></category>
		<category><![CDATA[3D]]></category>
		<category><![CDATA[assets]]></category>
		<category><![CDATA[components]]></category>
		<category><![CDATA[game]]></category>
		<category><![CDATA[GameObject]]></category>
		<category><![CDATA[hierarchy]]></category>
		<category><![CDATA[inspector]]></category>
		<category><![CDATA[introduction]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[projects]]></category>
		<category><![CDATA[rendering]]></category>
		<category><![CDATA[scene]]></category>
		<category><![CDATA[scripting]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[Unity 3.5]]></category>
		<category><![CDATA[Unity 4.0]]></category>
		<category><![CDATA[VCS]]></category>
		<category><![CDATA[version control]]></category>

		<guid isPermaLink="false">http://3dgep.com/?p=3246</guid>
		<description><![CDATA[Unity is a tool for creating and deploying games to PC, consoles, web and mobile devices. In this post, I will go through the steps to get Unity installed on your computer and I will introduce you to the basic features of Unity. <a href="http://3dgep.com/?p=3246">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
				<content:encoded><![CDATA[<p><div id="attachment_3247" class="wp-caption alignleft" style="width: 160px"><a href="http://unity3d.com/"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Icon-150x150.png" alt="Unity" title="Unity" width="150" height="150" class="size-thumbnail wp-image-3247" /></a><p class="wp-caption-text">Unity</p></div><br />
In this article, I will introduce you to the <a href="http://unity3d.com/" title="Unity" target="_blank">Unity game editor</a>. Unity is a tool for creating and deploying games to PC, consoles, web and mobile devices. In this post, I will go through the steps to get Unity installed on your computer and I will introduce you to the basic features of Unity. Unity makes it easy for anyone to get started making games. You will not need any previous game development experience to follow these articles but by the end, you will be prepared to start making your own games like a professional!</p>
<p><span id="more-3246"></span></p>
<div style="clear: both;"><div class='toc wptoc'>
<h2>Table of Contents</h2>
<ol class='toc-odd level-1'>
	<li>
		<a href="#Installing_Unity">Installing Unity</a>
	</li>
	<li>
		<a href="#Learning_the_Interface">Learning the Interface</a>
		<ol class='toc-even level-2'>
			<li>
				<a href="#The_Main_Menu">The Main Menu</a>
				<ol class='toc-odd level-3'>
					<li>
						<a href="#The_File_Menu">The File Menu</a>
					</li>
					<li>
						<a href="#The_Edit_Menu">The Edit Menu</a>
					</li>
					<li>
						<a href="#The_Assets_Menu">The Assets Menu</a>
					</li>
					<li>
						<a href="#GameObject_Menu">GameObject Menu</a>
					</li>
					<li>
						<a href="#The_Component_Menu">The Component Menu</a>
					</li>
					<li>
						<a href="#The_Terrain_Menu">The Terrain Menu</a>
					</li>
					<li>
						<a href="#The_Window_Menu">The Window Menu</a>
					</li>
					<li>
						<a href="#The_Help_Menu">The Help Menu</a>
					</li>
				</ol>
			<li>
				<a href="#The_Toolbar">The Toolbar</a>
				<ol class='toc-odd level-3'>
					<li>
						<a href="#Transform_Tools">Transform Tools</a>
						<ol class='toc-even level-4'>
							<li>
								<a href="#View_Manipulation">View Manipulation</a>
							</li>
							<li>
								<a href="#GameObject_Manipulation">GameObject Manipulation</a>
							</li>
						</ol>
					<li>
						<a href="#Gizmo_Tools">Gizmo Tools</a>
						<ol class='toc-even level-4'>
							<li>
								<a href="#Pivot">Pivot</a>
							</li>
							<li>
								<a href="#Center">Center</a>
							</li>
							<li>
								<a href="#Global">Global</a>
							</li>
							<li>
								<a href="#Local">Local</a>
							</li>
						</ol>
					<li>
						<a href="#Game_Player_Controls">Game Player Controls</a>
					</li>
					<li>
						<a href="#The_Layers_Tool">The Layers Tool</a>
					</li>
					<li>
						<a href="#The_Layout_Tool">The Layout Tool</a>
					</li>
				</ol>
			<li>
				<a href="#The_Editor_Windows">The Editor Windows</a>
				<ol class='toc-odd level-3'>
					<li>
						<a href="#The_Scene_View">The Scene View</a>
						<ol class='toc-even level-4'>
							<li>
								<a href="#Navigating_the_Scene_View">Navigating the Scene View</a>
							</li>
							<li>
								<a href="#Draw_Mode">Draw Mode</a>
							</li>
							<li>
								<a href="#Render_Mode">Render Mode</a>
							</li>
							<li>
								<a href="#Scene_Mode_Controls">Scene Mode Controls</a>
							</li>
							<li>
								<a href="#Search_Filter">Search Filter</a>
							</li>
						</ol>
</ol>
					<li>
						<a href="#The_Game_View">The Game View</a>
					</li>
					<li>
						<a href="#The_Inspector_View">The Inspector View</a>
					</li>
					<li>
						<a href="#The_Hierarchy_View">The Hierarchy View</a>
					</li>
					<li>
						<a href="#The_Project_View">The Project View</a>
					</li>
					<li>
						<a href="#The_Animation_View">The Animation View</a>
					</li>
					<li>
						<a href="#The_Profiler_View_Pro_Only">The Profiler View (Pro Only)</a>
					</li>
					<li>
						<a href="#The_Particle_Effect_View">The Particle Effect View</a>
					</li>
					<li>
						<a href="#The_Asset_Store_View">The Asset Store View</a>
					</li>
					<li>
						<a href="#The_Asset_Server_View_Team_License">The Asset Server View (Team License)</a>
					</li>
					<li>
						<a href="#Other_Windows">Other Windows</a>
						<ol class='toc-odd level-3'>
							<li>
								<a href="#Lightmapping">Lightmapping</a>
							</li>
							<li>
								<a href="#Occlusion_Culling_Pro_Only">Occlusion Culling (Pro Only)</a>
							</li>
							<li>
								<a href="#Navigation_Pro_Only">Navigation (Pro Only)</a>
							</li>
						</ol>
</ol>
					<li>
						<a href="#Creating_Your_First_Project">Creating Your First Project</a>
						<ol class='toc-even level-2'>
							<li>
								<a href="#Adding_Some_Content">Adding Some Content</a>
							</li>
							<li>
								<a href="#Adding_a_Light">Adding a Light</a>
							</li>
							<li>
								<a href="#Parenting_GameObjects">Parenting GameObjects</a>
							</li>
							<li>
								<a href="#Make_it_Spin">Make it Spin</a>
							</li>
						</ol>
					<li>
						<a href="#Adding_Your_Projects_to_Version_Control">Adding Your Projects to Version Control</a>
						<ol class='toc-even level-2'>
							<li>
								<a href="#Enable_Meta_File_Mode">Enable Meta File Mode</a>
							</li>
							<li>
								<a href="#Adding_to_Version_Control">Adding to Version Control</a>
							</li>
						</ol>
					<li>
						<a href="#More_Information">More Information</a>
					</li>
</ol>
</div>
<div class='wptoc-end'>&nbsp;</div></div>
<span id="Installing_Unity"><h1>Installing Unity</h1></span>
<p>The first thing you have to do before you can start using Unity is install it.  Navigate to <a href="http://unity3d.com/" title="Unity" target="_blank">http://unity3d.com/</a> and click the &#8220;Download&#8221; link on the top-right of the page.</p>
<p>On the download page, click the &#8220;<strong>Download Unity</strong>&#8221; button.  Once the file has been downloaded, execute the installer on your PC.</p>
<div id="attachment_3257" class="wp-caption alignnone" style="width: 523px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Installing-Unity-1.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Installing-Unity-1.png" alt="Installing Unity (1)" title="Installing Unity (1)" width="513" height="399" class="size-full wp-image-3257" /></a><p class="wp-caption-text">Installing Unity (1)</p></div>
<p>The Unity setup screen should appear.  Click the &#8220;<strong>Next</strong>&#8221; button.</p>
<p>Agree to the licensing terms to continue.</p>
<div id="attachment_3258" class="wp-caption alignnone" style="width: 523px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Installing-Unity-2.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Installing-Unity-2.png" alt="Installing Unity (2)" title="Installing Unity (2)" width="513" height="399" class="size-full wp-image-3258" /></a><p class="wp-caption-text">Installing Unity (2)</p></div>
<p>Select all of the available components options and click the &#8220;<strong>Next</strong>&#8221; button to continue.</p>
<div id="attachment_3261" class="wp-caption alignnone" style="width: 523px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Installing-Unity-3.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Installing-Unity-3.png" alt="Installing Unity (3)" title="Installing Unity (3)" width="513" height="399" class="size-full wp-image-3261" /></a><p class="wp-caption-text">Installing Unity (3)</p></div>
<p>Select the folder where you want Unity to be installed and click the &#8220;<strong>Install</strong>&#8221; button.</p>
<p>If everything went okay, you should see the following screen.</p>
<div id="attachment_3263" class="wp-caption alignnone" style="width: 523px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Installing-Unity-4.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Installing-Unity-4.png" alt="Installing Unity (4)" title="Installing Unity (4)" width="513" height="399" class="size-full wp-image-3263" /></a><p class="wp-caption-text">Installing Unity (4)</p></div>
<p>Click the &#8220;<strong>Finish</strong>&#8221; button to close the installer and run Unity.</p>
<p>Unity comes with an example project called &#8220;AngryBots&#8221; that you can open if you don&#8217;t yet have a Unity project to run. I will use this example project in this article to demonstrate the different parts of the Unity editor.  By default, the AngryBots example project is installed in &#8220;<strong>C:\Users\Public\Documents\Unity Projects</strong>&#8221; on Windows 7.</p>
<p>If you didn&#8217;t install the example project, or you would like to install a different example project, you can download additional example projects from the Unity Asset store which is accessible directly in the editor.</p>
<span id="Learning_the_Interface"><h1>Learning the Interface</h1></span>
<p>The first time you open the Unity editor, you will see a few of the default tabbed windows called Views open.</p>
<div id="attachment_3265" class="wp-caption alignnone" style="width: 1610px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Interface.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Interface.png" alt="Unity Interface" title="Unity Interface" width="1600" height="860" class="size-full wp-image-3265" /></a><p class="wp-caption-text">Unity Interface</p></div>
<p>The image above shows the Unity editor with the &#8220;Tall&#8221; layout applied.</p>
<span id="The_Main_Menu"><h2>The Main Menu</h2></span>
<p>The <strong>Main Menu</strong> is the menu at the top of the application window. It is organized into a logical set of &#8220;tasks&#8221; that you would need to access while you work on the project.</p>
<span id="The_File_Menu"><h3>The File Menu</h3></span>
<p>The <strong>File</strong> menu contains menu items that are used to create and open <strong>Scenes</strong> and <strong>Projects</strong>.  A Scene can be a single level of your game, or a scene can be used to define the main menu for your game.  A <strong>Project</strong> is the collection of things that is needed to create a game such as art assets, audio assets, scripts, and also the different game scenes.</p>
<div id="attachment_3267" class="wp-caption alignnone" style="width: 247px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-File-Menu.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-File-Menu.gif" alt="Unity - File Menu" title="Unity - File Menu" width="237" height="278" class="size-full wp-image-3267" /></a><p class="wp-caption-text">Unity &#8211; File Menu</p></div>
<span id="The_Edit_Menu"><h3>The Edit Menu</h3></span>
<p>The <strong>Edit</strong> menu contains the typical items you would expect in an edit menu such as <strong>Cut</strong>, <strong>Copy</strong>, <strong>Paste</strong>, <strong>Undo</strong>, <strong>Redo</strong> and it also contains items to modify the <strong>Editor Preferences</strong> as well as <strong>Project</strong> specific options and <strong>Render</strong> options.</p>
<div id="attachment_3271" class="wp-caption alignnone" style="width: 269px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Edit-Menu.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Edit-Menu.gif" alt="Unity - Edit Menu" title="Unity - Edit Menu" width="259" height="560" class="size-full wp-image-3271" /></a><p class="wp-caption-text">Unity &#8211; Edit Menu</p></div>
<span id="The_Assets_Menu"><h3>The Assets Menu</h3></span>
<p>The <strong>Asset</strong> menu is used for creating new assets or <strong>Importing</strong> assets from external files. You can also <strong>Import</strong> standard asset packages (standard asset packages are provided by Unity Technologies) as well as <strong>Import</strong> and <strong>Export</strong> custom asset packages for use in other projects (custom asset packages are user created).</p>
<div id="attachment_3288" class="wp-caption alignnone" style="width: 277px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Asset-Menu.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Asset-Menu.gif" alt="Unity - Asset Menu" title="Unity - Asset Menu" width="267" height="344" class="size-full wp-image-3288" /></a><p class="wp-caption-text">Unity &#8211; Asset Menu</p></div>
<p>Generally speaking Assets are the files that are created outside of Unity. Unity has fantastic support for a lot of different Asset types including 3D models, image formats, audio &#038; video formats, and XML file formats.</p>
<table>
<tr>
<th>Type</th>
<th>External Package</th>
<th>Extension</th>
<th>Requirements</th>
<tr>
<td rowspan="12" style="vertical-align: middle;">3D Model</td>
<td nowrap="nowrap">Maya</td>
<td align="center" nowrap>.ma &amp; .mb</td>
<td>Must have Maya 8.0 or newer installed.</td>
</tr>
<tr>
<td nowrap="nowrap">3D Studio Max</td>
<td align="center" nowrap="nowrap">.max</td>
<td>Must have 3D Studio Max installed.</td>
</tr>
<tr>
<td nowrap="nowrap">Cheetah3D</td>
<td align="center" nowrap="nowrap">.jas</td>
<td>Must have Cheetah3D 2.6 or newer installed.</td>
</tr>
<tr>
<td nowrap="nowrap">Cinema 4D</td>
<td align="center" nowrap="nowrap">.c4d</td>
<td>Must have Cinema 4D 8.5 or newer installed.</td>
</tr>
<tr>
<td nowrap="nowrap">Modo</td>
<td align="center" nowrap="nowrap">.lxo</td>
<td>Must have Modo 501 or newer installed.</td>
</tr>
<tr>
<td nowrap="nowrap">Lightwave</td>
<td align="center" nowrap="nowrap">.fbx</td>
<td>Models must be exported to FBX format.</td>
</tr>
<tr>
<td nowrap="nowrap">Blender</td>
<td align="center" nowrap="nowrap">.blend</td>
<td>Must have Blender 2.45-2.49 or 2.58 or newer (versions 2.50-2.57 broke the FBX exporter in Blender).</td>
</tr>
<tr>
<td nowrap="nowrap">COLLADA</td>
<td align="center" nowrap="nowrap">.dae</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td nowrap="nowrap">Autodesk FBX</td>
<td align="center" nowrap="nowrap">.fbx</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td nowrap="nowrap">Wavefront</td>
<td align="center" nowrap="nowrap">.obj</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td nowrap="nowrap">3D Studio</td>
<td align="center" nowrap="nowrap">.3ds</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td nowrap="nowrap">Drawing Interchange</td>
<td align="center" nowrap="nowrap">.dfx</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td rowspan="2" style="vertical-align: middle;">Image</td>
<td nowrap="nowrap">Photoshop</td>
<td align="center" nowrap="nowrap">.psd</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td nowrap="nowrap">Other Image Formats</td>
<td align="center">.jpg, .png, gif, .bmp, .tga, .iff, .pict, .dds, and more&#8230;</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td rowspan="3" style="vertical-align: middle;">Audio</td>
<td nowrap="nowrap">MP3</td>
<td align="center">.mp3</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td nowrap="nowrap">Ogg Vorbis</td>
<td align="center">.ogg</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td nowrap="nowrap">Other Audio Formats</td>
<td align="center">.aiff, .wav, .mod, .it, .sm3, and more&#8230;</td>
<td>Natively supported by Unity.</td>
</tr>
<tr>
<td style="vertical-align: middle;">Video</td>
<td nowrap="nowrap">Video Formats</td>
<td align="center">.mov, .avi, .asf, .mpg, .mpeg, .mp4</td>
<td>Video files are transcoded by Unity.</td>
</tr>
<tr>
<td style="vertical-align: middle;">Other</td>
<td nowrap="nowrap">Other File Formats</td>
<td align="center">.xml, .txt</td>
<td>Text files are not converted.</td>
</tr>
</table>
<p>Unity supports almost every file type that you would want to use in your own games.</p>
<span id="GameObject_Menu"><h3>GameObject Menu</h3></span>
<p>The <strong>GameObject</strong> menu contains items that allow you to <strong>Create</strong> and <strong>Manipulate</strong> <strong>GameObjects</strong>.</p>
<div id="attachment_3291" class="wp-caption alignnone" style="width: 302px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-GameObject-Menu.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-GameObject-Menu.gif" alt="Unity - GameObject Menu" title="Unity - GameObject Menu" width="292" height="269" class="size-full wp-image-3291" /></a><p class="wp-caption-text">Unity &#8211; GameObject Menu</p></div>
<p>A <strong>GameObject</strong> is something that exists in a <strong>Scene</strong>.  At its most basic level, a <strong>GameObject</strong> consists of a 3D position and an orientation in the <strong>Scene</strong>.  The <strong>GameObject</strong>&#8216;s position and orientation in the <strong>Scene</strong> is also called its <strong>Transform</strong>.</p>
<p>On its own, a <strong>GameObject</strong> does not do much. You must attach some <strong>Asset</strong> (as a Component) to a <strong>GameObject</strong> for it to be useful.  You can also link <strong>GameObject</strong>s together in a hierarchical fashion with a &#8220;parent-child&#8221; relationship and the &#8220;child&#8221; <strong>GameObject</strong>s will then be defined relative to its &#8220;parent&#8221; <strong>GameObject</strong>.  A <strong>GameObject</strong> can only have one parent so it is not possible to have the same <strong>GameObject</strong> linked to multiple parents but something similar can be achieved using <strong>Prefabs</strong> (which I will discuss later).</p>
<span id="The_Component_Menu"><h3>The Component Menu</h3></span>
<p>The <strong>Component</strong> menu lets you add <strong>Components</strong> to the currently selected <strong>GameObject</strong>.</p>
<div id="attachment_3293" class="wp-caption alignnone" style="width: 186px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Component-Menu.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Component-Menu.gif" alt="Unity - Component Menu" title="Unity - Component Menu" width="176" height="223" class="size-full wp-image-3293" /></a><p class="wp-caption-text">Unity &#8211; Component Menu</p></div>
<p>A <strong>Component</strong> must be added to a <strong>GameObject</strong> because a <strong>Component</strong> cannot exists on its own. The <strong>Components</strong> that are added to a <strong>GameObject</strong> define its behavior.</p>
<p>Unity has many types of Components that serve different purposes.</p>
<ul>
<li><strong>Mesh Component</strong>: used to render a 3D model at the location of the GameObject in the scene.</li>
<li><strong>Effect Component</strong>: allows you to create a particle effects, or special lens effects in your game.</li>
<li><strong>Physics Component</strong>: add physics to GameObjects so they can be physics controlled and able to interact with the player and other physics enabled GameObjects.</li>
<li><strong>Navigation Component (Pro Only)</strong>: Components that utilize the pathfinding functionality in Unity. The NavMesh funcitonality is only available for Pro licenses.</li>
<li><strong>Audio Components</strong>: add sound effects to your game.</li>
<li><strong>Rendering Components</strong>: components that control graphics related functionality such as cameras and lights.</li>
<li><strong>Miscellaneous Components</strong>: Components that don&#8217;t fit in their own category.</li>
</ul>
<p>You may see additional menu items in the <strong>Component</strong> menu if your project has any scripts which will be added to the menu when they are added to the project.</p>
<span id="The_Terrain_Menu"><h3>The Terrain Menu</h3></span>
<p>The Terrain menu has commands for creating and manipulating terrains.</p>
<div id="attachment_3300" class="wp-caption alignnone" style="width: 281px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Terrain-Menu.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Terrain-Menu.gif" alt="Unity - Terrain Menu" title="Unity - Terrain Menu" width="271" height="179" class="size-full wp-image-3300" /></a><p class="wp-caption-text">Unity &#8211; Terrain Menu</p></div>
<span id="The_Window_Menu"><h3>The Window Menu</h3></span>
<p>The <strong>Window</strong> menu allows you to show and hide the different windows in the Unity editor. You can also change the current window layout or save a custom layout.</p>
<div id="attachment_3302" class="wp-caption alignnone" style="width: 273px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Window-Menu.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Window-Menu.gif" alt="Unity - Window Menu" title="Unity - Window Menu" width="263" height="431" class="size-full wp-image-3302" /></a><p class="wp-caption-text">Unity &#8211; Window Menu</p></div>
<p>I will discuss the different windows in the following sections.</p>
<span id="The_Help_Menu"><h3>The Help Menu</h3></span>
<p>The <strong>Help</strong> menu provides commands for accessing the documentation and also for registering your Unity version with a Pro license.</p>
<div id="attachment_3305" class="wp-caption alignnone" style="width: 211px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Help-Menu.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Help-Menu.gif" alt="Unity - Help Menu" title="Unity - Help Menu" width="201" height="321" class="size-full wp-image-3305" /></a><p class="wp-caption-text">Unity &#8211; Help Menu</p></div>
<span id="The_Toolbar"><h2>The Toolbar</h2></span>
<p>The <strong>Toolbar</strong> contains a minimal set of tools that are required to interact with the <strong>Scene</strong> and to manipulate the <strong>GameObject</strong>s in the <strong>Scene</strong>.</p>
<div id="attachment_3307" class="wp-caption alignnone" style="width: 763px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Toolbar.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Toolbar.png" alt="Unity - Toolbar" title="Unity - Toolbar" width="753" height="56" class="size-full wp-image-3307" /></a><p class="wp-caption-text">Unity &#8211; Toolbar</p></div>
<span id="Transform_Tools"><h3>Transform Tools</h3></span>
<p>The Transform tools are probably the most common tool you&#8217;ll be using to interact with the <strong>Scene</strong> view and to manipulate the positions and orientations of the <strong>GameObject</strong>s.  However, once you learn the shortcut keys, you probably won&#8217;t use this tool directly very much.</p>
<span id="View_Manipulation"><h4>View Manipulation</h4></span>
<p>The first (left-most) button on this tool is the scene view manipulator and its functionality is dependent on whether you are pressing the <strong>Alt</strong> key (<strong>Command</strong> key on Mac) on the keyboard.  Pressing <strong>Q</strong> on the keyboard will switch to the view manipulation mode in the scene.</p>
<ul>
<li><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Move-View.gif" alt="Unity - Pan View" valign="middle"/> &#8211; (<strong>LMB</strong>) The <strong>Pan View</strong> button allows you to pan the scene view using the Left Mouse Button (<strong>LMB</strong>).  This option can also be accessed with the Middle Mouse Button (<strong>MMB</strong>)</li>
<li><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Rotate-View.gif" alt="Unity - Rotate View" valign="middle"/> &#8211; (<strong>Alt+LMB</strong>) The <strong>Rotate View</strong> allows you to rotate the scene view around the view pivot. This option can can be accessed by holding the <strong>Alt</strong> key on the keyboard and dragging in the Scene view with the Left Mouse Button (<strong>Alt+LMB</strong>).</li>
<li><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Zoom-View.gif" alt="Unity - Zoom View" valign="middle"/> &#8211; (<strong>Alt+RMB</strong>) The <strong>Zoom View</strong> allows you to zoom in or out. This option is accessed by holding the Alt key on the keyboard while dragging with the Right Mouse Button (<strong>Alt+RMB</strong>).</li>
</ul>
<span id="GameObject_Manipulation"><h4>GameObject Manipulation</h4></span>
<p>You can transform <strong>GameObject</strong>s using the <strong>Move</strong>, <strong>Rotate</strong>, and <strong>Scale</strong> tools.</p>
<ul>
<li><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Move-Tool.gif" alt="Unity - Move Tool" valign="middle" /> &#8211; (<strong>W</strong>) The <strong>Move</strong> button allows you to manipulate the translation of the currently selected GameObject. The shortcut key for this tool is the <strong>W</strong> key.</li>
<li><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Rotate-Tool.gif" alt="Unity - Rotate Tool" valign="middle"/> &#8211; (<strong>E</strong>) The <strong>Rotate</strong> button allows you to manipulate the orientation of the currently selected game object. The shortcut key for the rotate tool is the <strong>E</strong> key.</li>
<li><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Scale-Tool.gif" alt="Unity - Scale Tool" valign="middle" /> &#8211; (<strong>R</strong>) The <strong>Scale</strong> button allows you to manipulate the scale of the currently selected GameObject. The shortcut key for scaling an object is the <strong>R</strong> key.</li>
</ul>
<div id="attachment_3345" class="wp-caption alignnone" style="width: 594px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Transform-Gizmo2.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Transform-Gizmo2.png" alt="Unity - Transform Gizmo" title="Unity - Transform Gizmo" width="584" height="302" class="size-full wp-image-3345" /></a><p class="wp-caption-text">Unity &#8211; Transform Gizmo</p></div>
<p>The <strong>Transform Gizmo</strong> shown in the image above allows you to constrain the translation, rotation, and scale to a particular axis or axes.</p>
<p>Clicking on the <strong>Red</strong> gizmo handle allows you to constrain the manipulation in the <strong>X-axis</strong>.<br />
Clicking on the <strong>Green</strong> gizmo handle allows you to constrain the manipulation in the <strong>Y-axis</strong>.<br />
Clicking on the <strong>Blue</strong> gizmo handle allows you to constrain the manipulation in the <strong>Z-axis</strong>.</p>
<p>When using the <strong>Translate Gizmo</strong>, you can press the <strong>Shift</strong> key on the keyboard to constrain the movement to the <strong>View</strong> plane (motion is constrained to the virtual plane represented by the screen).</p>
<span id="Gizmo_Tools"><h3>Gizmo Tools</h3></span>
<p>The <strong>Transform Gizmo</strong> manipulation tools allow you to specify how the gizmo behaves.</p>
<div id="attachment_3335" class="wp-caption alignnone" style="width: 156px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Gizmo-Pivot-Global1.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Gizmo-Pivot-Global1.gif" alt="Unity - Gizmo Tool" title="Unity - Gizmo Tool" width="146" height="32" class="size-full wp-image-3335" /></a><p class="wp-caption-text">Unity &#8211; Gizmo Tool</p></div>
<span id="Pivot"><h4>Pivot</h4></span>
<p>You can specify that the <strong>Transform Gizmo</strong> should be relative to the GameObject&#8217;s pivot point. In this case, any transforms that you apply to the GameObject (or selected GameObjects) will be relative to that object&#8217;s pivot point.</p>
<div id="attachment_3333" class="wp-caption alignnone" style="width: 393px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Gizmo-Pivot-Global.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Gizmo-Pivot-Global.png" alt="Unity - Gizmo (Pivot, Global)" title="Unity - Gizmo (Pivot, Global)" width="383" height="309" class="size-full wp-image-3333" /></a><p class="wp-caption-text">Unity &#8211; Gizmo (Pivot, Global)</p></div>
<p>The image above shows that the <strong>Transform Gizmo</strong> is anchored to the currently selected GameObject&#8217;s pivot point.  When selecting multiple GameObjects, the pivot point will be anchored to the GameObject that was selected first.</p>
<span id="Center"><h4>Center</h4></span>
<p>You can also specify that the <strong>Transform Gizmo</strong> should be relative to the GameObject&#8217;s center point.  This may be different than the pivot point of the GameObject if the GameObject is parented to another GameObject in the scene <strong>Hierarchy</strong> or if it contains a model (or mesh) that does not have it&#8217;s pivot centered in the model.</p>
<div id="attachment_3338" class="wp-caption alignnone" style="width: 360px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Gizmo-Center-Global.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Gizmo-Center-Global.png" alt="Unity - Gizmo (Center, Global)" title="Unity - Gizmo (Center, Global)" width="350" height="288" class="size-full wp-image-3338" /></a><p class="wp-caption-text">Unity &#8211; Gizmo (Center, Global)</p></div>
<p>The image above shows that the <strong>Transform Gizmo</strong> is centered relative to all the currently selected game objects. Any rotations applied to the selected GameObjects will be relative to the center point of all of the currently selected GameObjects.</p>
<span id="Global"><h4>Global</h4></span>
<p>With <strong>Global</strong> selected in the Gizmo tool, translations and rotations will be applied in the global reference frame (that is, the global X-, Y-, and Z-axes). In this case the GameObject&#8217;s orientation will be ignored when using the Transform Gizmo to translate or rotate the GameObject.</p>
<div class="my-note">
Scaling a GameObject will always be applied in the GameObject&#8217;s Local space. Otherwise the GameObject might become skewed which is usually undesirable.
</div>
<div id="attachment_3342" class="wp-caption alignnone" style="width: 360px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Gizmo-Pivot-Global-2.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Gizmo-Pivot-Global-2.png" alt="Unity - Gizmo (Global)" title="Unity - Gizmo (Global)" width="350" height="288" class="size-full wp-image-3342" /></a><p class="wp-caption-text">Unity &#8211; Gizmo (Global)</p></div>
<p>You can see from the image above that the Transform Gizmo is still aligned to the Global Axis even after the GameObject has been rotated.</p>
<span id="Local"><h4>Local</h4></span>
<p>With <strong>Local</strong> selected in the Gizmo tool, translations and rotations will be applied in the GameObject&#8217;s local reference frame.  In this case, the GameObject&#8217;s current orientation will be taken into consideration when transforming the GameObject using the Transform Gizmo.</p>
<div id="attachment_3343" class="wp-caption alignnone" style="width: 360px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Gizmo-Pivot-Local.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Gizmo-Pivot-Local.png" alt="Unity - Gizmo (Pivot, Local)" title="Unity - Gizmo (Pivot, Local)" width="350" height="288" class="size-full wp-image-3343" /></a><p class="wp-caption-text">Unity &#8211; Gizmo (Local)</p></div>
<span id="Game_Player_Controls"><h3>Game Player Controls</h3></span>
<p>The <strong>Game Player</strong> controls allow you to play the game directly in the editor.</p>
<div id="attachment_3351" class="wp-caption alignnone" style="width: 310px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Game-Player-Controls1.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Game-Player-Controls1.png" alt="Unity - Game Player Controls (Play, Pause, Step)" title="Unity - Game Player Controls (Play, Pause, Step)" width="300" height="64" class="size-full wp-image-3351" /></a><p class="wp-caption-text">Unity &#8211; Game Player Controls (Play, Pause, Step)</p></div>
<p>The <strong>Game Player</strong> controls will turn blue when the game is currently running.</p>
<ul>
<li><strong>Play</strong>: Start/Stop the game play in the Game Window.</li>
<li><strong>Pause</strong>: Pauses the currently playing game. If the game is not playing, it will be started in the &#8220;Pause&#8221; state when you press the &#8220;Play&#8221; button.</li>
<li><strong>Step</strong>: Step and Pause the game play. Successively hitting this button will run the game in a single-step iterations of the game loop.</li>
</ul>
<span id="The_Layers_Tool"><h3>The Layers Tool</h3></span>
<p>Each GameObject can be assigned to a particular layer.  By default, newly created GameObjects are created in the &#8220;Default&#8221; layer.  The visibility of GameObjects in the Scene can be toggled on and off by selecting the layers in the layers visibility drop-down list.</p>
<div id="attachment_3354" class="wp-caption alignnone" style="width: 177px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Layer-Visibility.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Layer-Visibility.png" alt="Unity - Layer Visibility" title="Unity - Layer Visibility" width="167" height="192" class="size-full wp-image-3354" /></a><p class="wp-caption-text">Unity &#8211; Layer Visibility</p></div>
<span id="The_Layout_Tool"><h3>The Layout Tool</h3></span>
<p>The Layout drop-down list can be used to quickly set your workspace to a predefined layout.</p>
<div id="attachment_3355" class="wp-caption alignnone" style="width: 229px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Layout.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Layout.png" alt="Unity - Layout Tool" title="Unity - Layout Tool" width="219" height="193" class="size-full wp-image-3355" /></a><p class="wp-caption-text">Unity &#8211; Layout Tool</p></div>
<p>The Layout drop-down list also lets you save your current layout if you have made any changes to one of the default layouts. Saving your current layout allows you to create a set of layouts that you commonly like to use.</p>
<span id="The_Editor_Windows"><h2>The Editor Windows</h2></span>
<p>The Unity Editor currently has ten different windows that can be used to view different aspects of your game project.  By default, the <strong>Scene</strong>, <strong>Game</strong>, <strong>Hierachy</strong>, <strong>Project</strong>, and <strong>Inspector</strong> views are visible.  In this section, I will discuss each view and it&#8217;s uses.</p>
<span id="The_Scene_View"><h3>The Scene View</h3></span>
<p>The <strong>Scene View</strong> (Ctrl+1) is used to position and orientate the GameObjects in the scene.  Some components provide additional handles you can manipulate in the scene view when holding the Shift key on the keyboard.</p>
<div id="attachment_3361" class="wp-caption alignnone" style="width: 913px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Scene-View.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Scene-View.jpg" alt="Unity - Scene View" title="Unity - Scene View" width="903" height="783" class="size-full wp-image-3361" /></a><p class="wp-caption-text">Unity &#8211; Scene View</p></div>
<span id="Navigating_the_Scene_View"><h4>Navigating the Scene View</h4></span>
<p>There are multiple ways to navigate the scene view.</p>
<span id="Arrow_Keys"><h5>Arrow Keys</h5></span>
<p>If the Scene views have focus, you can use the arrow keys on the keyboard to fly through the level.  The <strong>Up</strong>/<strong>Down</strong> arrow keys will move the camera forward and backward relative to the direction the view.  The <strong>Left</strong>/<strong>Right</strong> keys will pan the view left and right respectively.</p>
<p>You can use the <strong>Shift</strong> key to double the movement speed.</p>
<span id="Flythrough_Mode"><h5>Flythrough Mode</h5></span>
<p>Holding down the Right Mouse Button (<strong>RMB</strong>) in the Scene view will allow you to Flythrough the scene using familiar FPS controls.  In this mode, you can use the <strong>WASD</strong> keys on the keyboard to move forward, left, back, and right (respectively).  Using the <strong>Q</strong> and <strong>E</strong> keys you can fly down and up (respectively).</p>
<p>You can use the <strong>Shift</strong> in this mode as well to double the movement speed.</p>
<span id="Zoom_to_Selected"><h5>Zoom to Selected</h5></span>
<p>Selecting a GameObject in either the Scene view or the Hierarchy will allow you to quickly zoom to that GameObject in the Scene view by pressing the <strong>F</strong> key on the keyboard while the mouse is over the Scene view. The Scene view will zoom to the GameObject (and all of it&#8217;s children) centered in the view.  This will also center the camera orbit on the GameObject.</p>
<span id="The_Scene_Gizmo"><h5>The Scene Gizmo</h5></span>
<p>You can use the Scene Gizmo to orient the current scene view.</p>
<div id="attachment_3393" class="wp-caption alignnone" style="width: 115px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Scene-Gizmo.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Scene-Gizmo.png" alt="Unity - Scene Gizmo" title="Unity - Scene Gizmo" width="105" height="105" class="size-full wp-image-3393" /></a><p class="wp-caption-text">Unity &#8211; Scene Gizmo</p></div>
<p>Clicking on any of the axis on the gizmo will snap the view to that orientation.  Clicking in the center of the gizmo will go back to <strong>Perspective</strong> view.</p>
<div id="attachment_3394" class="wp-caption alignnone" style="width: 923px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Scene-View1.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Scene-View1.jpg" alt="Unity - Scene View" title="Unity - Scene View" width="913" height="798" class="size-full wp-image-3394" /></a><p class="wp-caption-text">Unity &#8211; Scene View</p></div>
<p><strong>Shift-Click</strong> on the middle of the Scene Gizmo to toggle between <strong>Perspective</strong> view and <strong>Isometric</strong> view.</p>
<div id="attachment_3396" class="wp-caption alignnone" style="width: 754px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Perspective-vs-Iso.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Perspective-vs-Iso.jpg" alt="Unity - Perspective vs Iso" title="Unity - Perspective vs Iso" width="744" height="688" class="size-full wp-image-3396" /></a><p class="wp-caption-text">Unity &#8211; Perspective vs Iso</p></div>
<span id="Draw_Mode"><h4>Draw Mode</h4></span>
<p>You can change the way the scene is viewed using the <strong>Draw Mode</strong> drop-down box.</p>
<div id="attachment_3363" class="wp-caption alignnone" style="width: 210px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-View-Mode.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-View-Mode.gif" alt="Unity - Draw Mode" title="Unity - View Mode" width="200" height="153" class="size-full wp-image-3363" /></a><p class="wp-caption-text">Unity &#8211; Draw Mode</p></div>
<span id="Textured_Draw_Mode"><h5>Textured Draw Mode</h5></span>
<p>The <strong>Textured</strong> draw mode allows you to see the scene with all of the models textured.</p>
<div id="attachment_3361" class="wp-caption alignnone" style="width: 913px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Scene-View.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Scene-View.jpg" alt="Unity - Scene View" title="Unity - Scene View" width="903" height="783" class="size-full wp-image-3361" /></a><p class="wp-caption-text">Unity &#8211; Scene View (Textured)</p></div>
<span id="Wireframe_Draw_Mode"><h5>Wireframe Draw Mode</h5></span>
<p>In <strong>Wireframe</strong> draw mode, all of the meshes are drawn using their wireframe representation.</p>
<div id="attachment_3364" class="wp-caption alignnone" style="width: 913px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Wireframe-View.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Wireframe-View.jpg" alt="Unity - Wireframe View" title="Unity - Wireframe View" width="903" height="783" class="size-full wp-image-3364" /></a><p class="wp-caption-text">Unity &#8211; Wireframe View</p></div>
<span id="Tex_8211_Wire_Draw_Mode"><h5>Tex &#8211; Wire Draw Mode</h5></span>
<p>In <strong>Tex &#8211; Wire</strong> draw mode, you see the textured models with their wireframe representation drawn on top of them.</p>
<div id="attachment_3365" class="wp-caption alignnone" style="width: 913px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Tex-Wire.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Tex-Wire.jpg" alt="Unity - Tex - Wire" title="Unity - Tex - Wire" width="903" height="783" class="size-full wp-image-3365" /></a><p class="wp-caption-text">Unity &#8211; Tex &#8211; Wire</p></div>
<span id="Render_Paths_Draw_Mode"><h5>Render Paths Draw Mode</h5></span>
<p>In <strong>Render Paths</strong> draw mode, each object is shaded based on the rendering path used to render the object.</p>
<ul>
<li><strong>Green</strong> &#8211; Deferred Rendering.</li>
<li><strong>Yellow</strong> &#8211; Forward Rendering.</li>
<li><strong>Red</strong> &#8211; Vertex-Lit Rendering.</li>
</ul>
<div id="attachment_3367" class="wp-caption alignnone" style="width: 913px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Render-Paths.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Render-Paths.jpg" alt="Unity - Render Paths" title="Unity - Render Paths" width="903" height="783" class="size-full wp-image-3367" /></a><p class="wp-caption-text">Unity &#8211; Render Paths</p></div>
<span id="Lightmap_Resolution_Draw_Mode"><h5>Lightmap Resolution Draw Mode</h5></span>
<p>The <strong>Lightmap Resolution</strong> draw mode shows the textured objects with an overlay of a checkered grid which represents the resolution of the lightmaps for each object.</p>
<div id="attachment_3369" class="wp-caption alignnone" style="width: 913px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Lightmap-Resolution.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Lightmap-Resolution.jpg" alt="Unity - Lightmap Resolution" title="Unity - Lightmap Resolution" width="903" height="783" class="size-full wp-image-3369" /></a><p class="wp-caption-text">Unity &#8211; Lightmap Resolution</p></div>
<span id="Light_Probes_Draw_Mode"><h5>Light Probes Draw Mode</h5></span>
<p>With the <strong>Light Probes</strong> draw mode selected, you can visualize which light probes will effect the currently selected object.  </p>
<p>Note: The AngryBots sample project does not use light probes so selecting this view mode with the AngryBots scene does not look any different than the Textured view mode.</p>
<span id="Render_Mode"><h4>Render Mode</h4></span>
<p>The <strong>Render Mode</strong> drop-down box allows you to select the current render mode for the scene.</p>
<div id="attachment_3374" class="wp-caption alignnone" style="width: 151px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Render-Mode.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Render-Mode.jpg" alt="Unity - Render Mode" title="Unity - Render Mode" width="141" height="110" class="size-full wp-image-3374" /></a><p class="wp-caption-text">Unity &#8211; Render Mode</p></div>
<span id="RGB_Render_Mode"><h5>RGB Render Mode</h5></span>
<p>The default mode is <strong>RGB</strong> render mode.  In this render mode, object are rendered normally.</p>
<div id="attachment_3375" class="wp-caption alignnone" style="width: 822px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-RGB.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-RGB.jpg" alt="Unity - RGB Render Mode" title="Unity - RGB Render Mode" width="812" height="799" class="size-full wp-image-3375" /></a><p class="wp-caption-text">Unity &#8211; RGB Render Mode</p></div>
<span id="Alpha_Render_Mode"><h5>Alpha Render Mode</h5></span>
<p>The <strong>Alpha</strong> render mode displays the alpha value of the objects texture or material.  This does not mean that objects that are drawn black in this render mode will be transparent. They must have a transparent material applied on them in order to be rendered in the transparency pass.</p>
<div id="attachment_3379" class="wp-caption alignnone" style="width: 815px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Alpha-Render-Mode.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Alpha-Render-Mode.jpg" alt="Unity - Alpha Render Mode" title="Unity - Alpha Render Mode" width="805" height="799" class="size-full wp-image-3379" /></a><p class="wp-caption-text">Unity &#8211; Alpha Render Mode</p></div>
<span id="Overdraw_Render_Mode"><h5>Overdraw Render Mode</h5></span>
<p>In <strong>Overdraw</strong> render mode you can see where objects are drawn over top of other objects. Darker areas have less overdraw where brighter areas indicate overdraw. </p>
<p>Excessive overdraw could result in poor rendering performance but is sometimes unavoidable.</p>
<div id="attachment_3381" class="wp-caption alignnone" style="width: 815px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Overdraw-Render-Mode.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Overdraw-Render-Mode.jpg" alt="Unity - Overdraw Render Mode" title="Unity - Overdraw Render Mode" width="805" height="799" class="size-full wp-image-3381" /></a><p class="wp-caption-text">Unity &#8211; Overdraw Render Mode</p></div>
<span id="Mipmaps_Render_Mode"><h5>Mipmaps Render Mode</h5></span>
<p>In <b>Mipmaps</b> render mode you can visualize ideal texture sizes using a color code.</p>
<ul>
<li><strong>Red</strong>: The texture is larger than necessary.</li>
<li><strong>Blue</strong>: The texture could be larger.</li>
</ul>
<p>Keep in mind that the resulting colors is dependent on the current resolution of the screen and the distance the camera is away from the objects.  Generally, you should see objects turning blue when you move the camera close to them and objects that are far away will generally be red.  Unity will automatically generate mipmaps for your textures when they are imported.</p>
<div id="attachment_3382" class="wp-caption alignnone" style="width: 815px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Mipmaps-Render-Mode.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Mipmaps-Render-Mode.jpg" alt="Unity - Mipmaps Render Mode" title="Unity - Mipmaps Render Mode" width="805" height="799" class="size-full wp-image-3382" /></a><p class="wp-caption-text">Unity &#8211; Mipmaps Render Mode</p></div>
<span id="Scene_Mode_Controls"><h4>Scene Mode Controls</h4></span>
<p>The <strong>Scene Mode</strong> controls allow you to enable or disable different aspects of the scene view.</p>
<div id="attachment_3385" class="wp-caption alignnone" style="width: 168px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Scene-Mode-Controls.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Scene-Mode-Controls.jpg" alt="Unity - Scene Mode Controls" title="Unity - Scene Mode Controls" width="158" height="36" class="size-full wp-image-3385" /></a><p class="wp-caption-text">Unity &#8211; Scene Mode Controls</p></div>
<ul>
<li><strong>Scene Lighting</strong>: <img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Scene-Lighting.gif" alt="Unity - Scene Lighting" valign="middle" /> Toggle the game lighting or the scene default lighting.</li>
<li><strong>Game Overlay</strong>: <img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Overlay-Mode.gif" alt="Unity - Game Overlay" valign="middle" /> Toggle the display of Skyboxes and GUI Elements in the Scene view.</li>
<li><strong>Audition Mode</strong>: <img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Audition-Mode.gif" alt="Unity - Audition Mode" valign="middle" /> Toggles playing of audio sources in the scene view.</li>
</ul>
<span id="Search_Filter"><h4>Search Filter</h4></span>
<p>You can use the object search filter on the top-right side of the Scene view to quickly isolate specific game objects.</p>
<div id="attachment_3390" class="wp-caption alignnone" style="width: 815px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Search-Filter.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Search-Filter.jpg" alt="Unity - Search Filter" title="Unity - Search Filter" width="805" height="799" class="size-full wp-image-3390" /></a><p class="wp-caption-text">Unity &#8211; Search Filter</p></div>
<p>In this case, I filter on objects with the name &#8220;Player&#8221;. The search filter is capable of filtering using partial names so both the &#8220;Player&#8221; GameObjects are isolated and the &#8220;PlayerSlideDoor&#8221; GameObjects are also isolated in the scene view.</p>
<span id="The_Game_View"><h2>The Game View</h2></span>
<p>The <strong>Game View</strong> (Ctrl+2) allows you to see how the game will look during production.</p>
<div id="attachment_3402" class="wp-caption alignnone" style="width: 745px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Game-View.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Game-View.jpg" alt="Unity - Game View" title="Unity - Game View" width="735" height="693" class="size-full wp-image-3402" /></a><p class="wp-caption-text">Unity &#8211; Game View</p></div>
<p>On the top of the window, you will see the <strong>Aspect</strong> drop-down menu, the <strong>Maximize on Play</strong> toggle button, the <strong>Stats</strong> toggle button, and the <strong>Gizmos</strong> toggle.</p>
<ul>
<li><strong>Aspect</strong>: The Aspect drop-down menu allows you to force the aspect ratio of the Game View so that you can see how your game will play at different aspect ratios.</li>
<li><strong>Maximize on Play</strong>: This toggle button will cause the Game View to maximize to 100% of the editor window.</li>
<li><strong>Stats</strong>: The Stats toggle button will toggle the display of the performance statistics.</li>
<li><strong>Gizoms</strong>: Pressing this button will allow you to visualize the Gizmos that are usually only drawn in the Scene view.</li>
</ul>
<div id="attachment_3404" class="wp-caption alignnone" style="width: 853px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Game-View-Stats-On.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Game-View-Stats-On.jpg" alt="Unity - Game View (Stats On)" title="Unity - Game View (Stats On)" width="843" height="698" class="size-full wp-image-3404" /></a><p class="wp-caption-text">Unity &#8211; Game View (Stats On)</p></div>
<span id="The_Inspector_View"><h2>The Inspector View</h2></span>
<p>The <strong>Inspector View</strong> (Ctrl+3) shows you the properties of the currently selected GameObject and all of it&#8217;s Components.</p>
<div id="attachment_3408" class="wp-caption alignnone" style="width: 487px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Inspector-View.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Inspector-View.gif" alt="Unity - Inspector View" title="Unity - Inspector View" width="477" height="1081" class="size-full wp-image-3408" /></a><p class="wp-caption-text">Unity &#8211; Inspector View</p></div>
<p>One component that is common to all GameObjects is the <strong>Transform</strong> component. You will never see a GameObject without this component and it is impossible to remove the Transform component from a GameObject.</p>
<p>We will use the <strong>Inspector</strong> view more when I discuss Components and game scripting.</p>
<span id="The_Hierarchy_View"><h2>The Hierarchy View</h2></span>
<p>The <strong>Hierarchy View</strong> (Ctrl+4) shows all of the GameObjects in your scene. You can either select a GameObject directly from the Scene View or you can use the Hierarchy view to select a GameObject that exists in your scene.</p>
<div id="attachment_3410" class="wp-caption alignnone" style="width: 326px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Hierarchy-View.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Hierarchy-View.gif" alt="Unity - Hierarchy View" title="Unity - Hierarchy View" width="316" height="485" class="size-full wp-image-3410" /></a><p class="wp-caption-text">Unity &#8211; Hierarchy View</p></div>
<p>Using the <img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Hierarchy-View1.gif" alt="Unity - Create Game Button" valign="middle" /> (create new GameObject) you can quickly add a new GameObject to the scene based on one of the GameObject templates provided.</p>
<span id="The_Project_View"><h2>The Project View</h2></span>
<p>The <strong>Project View</strong> (Ctrl+5) is a direct reflection of the <strong>Asset</strong> folder in your game&#8217;s root folder on your file system.</p>
<div id="attachment_3414" class="wp-caption alignnone" style="width: 329px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Project-View.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Project-View.gif" alt="Unity - Project View" title="Unity - Project View" width="319" height="453" class="size-full wp-image-3414" /></a><p class="wp-caption-text">Unity &#8211; Project View</p></div>
<p>In the Project View, you can use the <img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Hierarchy-View1.gif" alt="Unity - Create New Button" valign="middle" /> to add a new asset type to your game assets.</p>
<p>I will discuss the project view in more detail when we create a new project from scratch.</p>
<span id="The_Animation_View"><h2>The Animation View</h2></span>
<p>The <strong>Animation View</strong> (Ctrl+6) allows you to create and modify Animation clips on the currently selected GameObject.</p>
<div id="attachment_3416" class="wp-caption alignnone" style="width: 734px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Animation-View.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Animation-View.gif" alt="Unity - Animation View" title="Unity - Animation View" width="724" height="514" class="size-full wp-image-3416" /></a><p class="wp-caption-text">Unity &#8211; Animation View</p></div>
<p>I will discuss how to use the Animation view in a future article.</p>
<span id="The_Profiler_View_Pro_Only"><h2>The Profiler View (Pro Only)</h2></span>
<p>The <strong>Profiler View</strong> (Ctrl+7) allows you to profile and optimize certain aspects of your game.</p>
<div id="attachment_3418" class="wp-caption alignnone" style="width: 812px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Profiler-View.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Profiler-View.gif" alt="Unity - Profiler View" title="Unity - Profiler View" width="802" height="648" class="size-full wp-image-3418" /></a><p class="wp-caption-text">Unity &#8211; Profiler View</p></div>
<p>The Profiler View is only available in the pro version of Unity.</p>
<span id="The_Particle_Effect_View"><h2>The Particle Effect View</h2></span>
<p>The <strong>Particle Effect View</strong> (Ctrl+8) is used to manipulate particle effects.</p>
<div id="attachment_3419" class="wp-caption alignnone" style="width: 943px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Particle-Effects-View.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Particle-Effects-View.gif" alt="Unity - Particle Effects View" title="Unity - Particle Effects View" width="933" height="776" class="size-full wp-image-3419" /></a><p class="wp-caption-text">Unity &#8211; Particle Effects View</p></div>
<p>I will discuss creating particle effects in another article.</p>
<span id="The_Asset_Store_View"><h2>The Asset Store View</h2></span>
<p>You can use the <strong>Asset Store View</strong> to download plug-ins and content that can be used in your Unity project.</p>
<div id="attachment_3420" class="wp-caption alignnone" style="width: 1110px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Asset-Store.jpg"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Asset-Store.jpg" alt="Unity - Asset Store" title="Unity - Asset Store" width="1100" height="836" class="size-full wp-image-3420" /></a><p class="wp-caption-text">Unity &#8211; Asset Store</p></div>
<p>The Asset Store has a lot of free and paid plug-ins and game content.</p>
<span id="The_Asset_Server_View_Team_License"><h2>The Asset Server View (Team License)</h2></span>
<p>The <strong>Asset Server View</strong> requires the Asset server license or a Team License to access it.  The <strong>Asset Server</strong> (Ctrl-0) is a content versioning system that makes it easier to share code when working in large teams.</p>
<span id="Other_Windows"><h2>Other Windows</h2></span>
<p>There are several other windows that you can also access from the <strong>Window</strong> menu. </p>
<span id="Lightmapping"><h3>Lightmapping</h3></span>
<p>The Lightmapping view allows you to access the lightmapping settings and controls for the current scene.  Lightmapping is used to apply a pre-rendered version of the lighting contributions to static objects in the scene.</p>
<p>Both the free version and the pro version of Unity allow you to access the Lightmapping view, the pro version has a lot of extra settings that cannot be accessed in the free version.</p>
<div id="attachment_3422" class="wp-caption alignnone" style="width: 370px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Lightmappig-View.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Lightmappig-View.gif" alt="Unity - Lightmappig View" title="Unity - Lightmappig View" width="360" height="695" class="size-full wp-image-3422" /></a><p class="wp-caption-text">Unity &#8211; Lightmappig View</p></div>
<p>I will discuss Lightmapping in more detail in another article.</p>
<span id="Occlusion_Culling_Pro_Only"><h3>Occlusion Culling (Pro Only)</h3></span>
<p>The <strong>Occlusion Culling View</strong> allows you to specify parameters to generate the occlusion data.  You can bake the occlusion data as a pre-process step. This allows Unity to optimize the visibility determination of GameObjects and reduce the chance that occluded objects are rendered.</p>
<div id="attachment_3423" class="wp-caption alignnone" style="width: 450px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Occlusion-Culling.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Occlusion-Culling.gif" alt="Unity - Occlusion Culling" title="Unity - Occlusion Culling" width="440" height="426" class="size-full wp-image-3423" /></a><p class="wp-caption-text">Unity &#8211; Occlusion Culling</p></div>
<span id="Navigation_Pro_Only"><h3>Navigation (Pro Only)</h3></span>
<p>The <strong>Navigation View</strong> allows you to generate navigation information for use by the game AI.</p>
<div id="attachment_3425" class="wp-caption alignnone" style="width: 334px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Navigation-View.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Navigation-View.gif" alt="Unity - Navigation View" title="Unity - Navigation View" width="324" height="515" class="size-full wp-image-3425" /></a><p class="wp-caption-text">Unity &#8211; Navigation View</p></div>
<span id="Creating_Your_First_Project"><h1>Creating Your First Project</h1></span>
<p>Now that we have a good understanding of all of the different parts of the Unity Editor, let&#8217;s put that knowledge to good use by creating our first project.</p>
<p>Open the Unity Editor if it is not open already.  By default, Unity will open the last opened project project automatically. If this is the first time using Unity, the <strong>Unity &#8211; Project Wizard</strong> dialog will appear.</p>
<div class="my-note">
If you are working with multiple Unity projects, you may want to show the Project Wizard every time you open the Unity Editor. To change this behavior, choose <strong>Edit -> Preferences&#8230;</strong> from the main menu.</p>
<div id="attachment_3429" class="wp-caption alignnone" style="width: 526px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Editor-Preferences.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Editor-Preferences.gif" alt="Unity - Editor Preferences" title="Unity - Editor Preferences" width="516" height="434" class="size-full wp-image-3429" /></a><p class="wp-caption-text">Unity &#8211; Editor Preferences</p></div>
<p>Check the &#8220;<strong>Always Show Project Wizard</strong>&#8221; option to show the Project Wizard when you open the Unity Editor instead of automatically opening the previously opened project.
</div>
<p>If the <strong>Project Wizard</strong> dialog did not appear, select <strong>File -> New Project&#8230;</strong> from the main menu.</p>
<p>Select the &#8220;<strong>Create New Project</strong>&#8221; tab.</p>
<div id="attachment_3430" class="wp-caption alignnone" style="width: 581px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Project-Wizard.gif"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Project-Wizard.gif" alt="Unity - Project Wizard" title="Unity - Project Wizard" width="571" height="365" class="size-full wp-image-3430" /></a><p class="wp-caption-text">Unity &#8211; Project Wizard</p></div>
<p>Choose a location for your project. This will become the root directory for your project.</p>
<p>Select any standard packages that you want to include in your project. If you have a pro license, you may see more packages marked (Pro Only).  You can include these packages in your project but some of the features used in those packages will be unavailable to people using the free version of Unity.</p>
<div class="my-note">
Don&#8217;t worry if you don&#8217;t select any of the standard packages when you create your new project. You will be able to add any of the standard packages to your project at any time by selecting <strong>Assets -> Import Package</strong> from the main menu.
</div>
<p>Click the <strong>Create</strong> button to create a new project.</p>
<p>Your new project should appear in the Unity editor with an untitled scene.  There should be only the Main Camera GameObject in your scene.</p>
<div id="attachment_3435" class="wp-caption alignnone" style="width: 1050px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-New-Project.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-New-Project.png" alt="Unity - New Project" title="Unity - New Project" width="1040" height="784" class="size-full wp-image-3435" /></a><p class="wp-caption-text">Unity &#8211; New Project</p></div>
<span id="Adding_Some_Content"><h2>Adding Some Content</h2></span>
<p>For this tutorial, we&#8217;ll just add a rotating cube to the scene.  I will introduce more complicated topics in later articles.</p>
<p>Select <strong>GameObject -> Create Other -> Cube</strong> from the main menu.</p>
<div id="attachment_3436" class="wp-caption alignnone" style="width: 1050px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Create-Cube.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Create-Cube.png" alt="Unity - Create Cube" title="Unity - Create Cube" width="1040" height="784" class="size-full wp-image-3436" /></a><p class="wp-caption-text">Unity &#8211; Create Cube</p></div>
<p>A new GameObject with the name &#8220;<strong>Cube</strong>&#8221; will be created in the center of the view.</p>
<div id="attachment_3437" class="wp-caption alignnone" style="width: 1050px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-New-Cube.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-New-Cube.png" alt="Unity - New Cube" title="Unity - New Cube" width="1040" height="784" class="size-full wp-image-3437" /></a><p class="wp-caption-text">Unity &#8211; New Cube</p></div>
<p>We also want to make sure the <strong>Main Camera</strong> GameObject is aiming at the <strong>Cube</strong>. To do this, select the &#8220;<strong>Main Camera</strong>&#8221; GameObject and position and rotate it so that it is pointing at the <strong>Cube</strong>.</p>
<div class="my-note">
This can be done quickly by selecting the <strong>Cube</strong> GameObject in either the <strong>Scene</strong> or the <strong>Hierarchy</strong> views and pressing the &#8220;<strong>F</strong>&#8221; (focus view) key on the keyboard while the mouse cursor is in the <strong>Scene</strong> view.  With the <strong>Scene</strong> view now focused on the cube, select the <strong>Main Camera</strong> in the <strong>Hierarchy</strong> view and select &#8220;<strong>GameObject -> Align With View (Ctrl+Shift+F)</strong>&#8221; from the main menu.
</div>
<p>You should see something similar to what is shown below.</p>
<div id="attachment_3439" class="wp-caption alignnone" style="width: 1050px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Focus-Cube.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Focus-Cube.png" alt="Unity - Focus Cube" title="Unity - Focus Cube" width="1040" height="784" class="size-full wp-image-3439" /></a><p class="wp-caption-text">Unity &#8211; Focus Cube</p></div>
<p>If you play the game now by pressing the &#8220;<strong>Play</strong>&#8221; button, you will see a pretty boring silhouette of a cube.  Maybe it will look better with a little bit of lighting?</p>
<span id="Adding_a_Light"><h2>Adding a Light</h2></span>
<p>Let&#8217;s add a light to the scene so we can see that our cube has some depth.</p>
<p>Select either &#8220;<strong>GameObject -> Create Other -> Directional Light</strong>&#8221; from the main menu or use the &#8220;<strong>Create -> Directional Light</strong>&#8221; drop-down box in the <strong>Hierarchy</strong> view to create a new GameObject with a directional Light component.</p>
<div id="attachment_3441" class="wp-caption alignnone" style="width: 1050px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Scene-with-Directional-Light.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Scene-with-Directional-Light.png" alt="Unity - Scene with Directional Light" title="Unity - Scene with Directional Light" width="1040" height="784" class="size-full wp-image-3441" /></a><p class="wp-caption-text">Unity &#8211; Scene with Directional Light</p></div>
<span id="Parenting_GameObjects"><h2>Parenting GameObjects</h2></span>
<p>The position of a directional light doesn&#8217;t have any influence on how a object is lit but its direction is important.  I want to have the light always pointing in the same direction as the Main Camera so that whatever it is I&#8217;m looking at will be lit consistently across it&#8217;s faces and I&#8217;ll never look at the dark side of the object.</p>
<p>In the <strong>Hierarchy</strong> view, use the mouse button to (left-)click and drag the <strong>Directional Light</strong> GameObject and drop it on top of the <strong>Main Camera</strong> GameObject. </p>
<div id="attachment_3443" class="wp-caption alignnone" style="width: 1050px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Parenting-Game-Objects.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Parenting-Game-Objects.png" alt="Unity - Parenting Game Objects" title="Unity - Parenting Game Objects" width="1040" height="784" class="size-full wp-image-3443" /></a><p class="wp-caption-text">Unity &#8211; Parenting Game Objects</p></div>
<p>Doing this will cause the <strong>Directional Light</strong> GameObject to inherit its position and orientation to be relative to the <strong>Main Camera</strong> GameObject.</p>
<p>You may notice, that parenting a GameObject to another does not change its position or orientation in the scene view.  Unity will modify the parented GameObject&#8217;s local position and orientation so that it remains in it&#8217;s initial position.  However, if we move the <strong>Main Camera</strong> GameObject, the <strong>Directional Light</strong> will be moved along with it.</p>
<p>Parenting one GameObject to another is good way to group many GameObjects together that have a commonality.  It is not uncommon to create an empty GameObject (a GameObject with no Components) where its only purpose is to act as a parent to all the GameObjects in a group.</p>
<p>Since we want the <strong>Directional Light</strong> to always point in the same direction as the <strong>Main Camera</strong> and we&#8217;ve parented the light to the camera, we can simply set the <strong>Directional Light</strong>&#8216;s local position and orientation to <strong>0</strong>.</p>
<p>Select the <strong>Directional Light</strong> in the Hierarchy view and set its X, Y, and Z Position properties to 0 and its X, Y, Z Rotation properties to 0. Leave the X, Y, and Z Scale properties at 1.</p>
<div id="attachment_3447" class="wp-caption alignnone" style="width: 1050px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Directional-Light-Zero-Transforms.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Directional-Light-Zero-Transforms.png" alt="Unity - Directional Light (Zero Transforms)" title="Unity - Directional Light (Zero Transforms)" width="1040" height="784" class="size-full wp-image-3447" /></a><p class="wp-caption-text">Unity &#8211; Directional Light (Zero Transforms)</p></div>
<p>To confirm that the light is pointing in the same direction as the <strong>Main Camera</strong>, select the <strong>Main Camera</strong> GameObject from the <strong>Hierarchy</strong> view and press the &#8220;<strong>F</strong>&#8221; (focus view) key while the mouse cursor is over the <strong>Scene</strong> view.  The <strong>Scene</strong> view should zoom out so that both the <strong>Main Camera</strong> and the <strong>Directional Light</strong> are in view.  Use the <strong>Alt+LMB</strong> combination to rotate the <strong>Scene</strong> view.</p>
<div id="attachment_3450" class="wp-caption alignnone" style="width: 1050px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Directional-Light-Aligned-to-Main-Camera.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Directional-Light-Aligned-to-Main-Camera.png" alt="Unity - Directional Light Aligned to Main Camera" title="Unity - Directional Light Aligned to Main Camera" width="1040" height="784" class="size-full wp-image-3450" /></a><p class="wp-caption-text">Unity &#8211; Directional Light Aligned to Main Camera</p></div>
<p>As you can see from the image, the light rays coming from the <strong>Directional Light</strong> GameObject are pointing in the same direction as the <strong>Main Camera</strong>.</p>
<p>Pressing &#8220;<strong>Play</strong>&#8221; now should show a cube that is lit by the directional light.</p>
<span id="Make_it_Spin"><h2>Make it Spin</h2></span>
<p>Now let&#8217;s add some action! We&#8217;re going to make the cube spin slowly.</p>
<p>In the <strong>Project</strong> view, create a new folder called <strong>Scripts</strong> (Either <strong>right-click</strong> in the <strong>Project</strong> view and select <strong>Create -> Folder</strong> from the pop-up menu that appears, or select &#8220;<strong>Folder</strong>&#8221; from the <strong>Create</strong> drop-down menu at the top of the <strong>Project</strong> view).  Rename the new folder to &#8220;<strong>Scripts</strong>&#8221; by (single) left-clicking on the new folder in the <strong>Project</strong> view or press &#8220;<strong>F2</strong>&#8221; on the keyboard while the new folder is selected in the <strong>Project</strong> view.</p>
<p>Right-click on the <strong>Scripts</strong> folder and select &#8220;<strong>Create -> JavaScript</strong>&#8221; from the pop-up menu that appears.</p>
<p>Rename the new JavaScript file to &#8220;<strong>Rotation</strong>&#8220;.</p>
<div class="my-note">
If you now open Windows Explorer and navigate to the folder where your project exists, you will notice that the <strong>Assets</strong> folder mirrors the file structure of the <strong>Project</strong> view.  The Project view is the same as the files contained in the Asset folder in your project&#8217;s root folder.  Any changes made to files in the Project view will be directly reflected on your computers file system.
</div>
<p>Open the JavaScript asset in the script editor by double-clicking on the Script asset in the <strong>Project</strong> view. (Unity comes with the MonoDevelop editor for editing script assets).</p>
<div id="attachment_3454" class="wp-caption alignnone" style="width: 1089px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-MonoDevelop.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-MonoDevelop.png" alt="Unity - MonoDevelop" title="Unity - MonoDevelop" width="1079" height="719" class="size-full wp-image-3454" /></a><p class="wp-caption-text">Unity &#8211; MonoDevelop</p></div>
<p>Copy-Paste the following code into the <strong>Rotation.js</strong> file.</p>
<div class="notranslate">
<pre class="brush:js;toolbar:false;first-line:1;" title="Rotation.js">
#pragma strict

function Update () {
	transform.Rotate( Vector3.up * ( 90 * Time.deltaTime ) ); 
}
</pre>
</div>
<p>Save the file and return to the Unity Editor.</p>
<p>Now drag and drop the <strong>Rotation</strong> script asset from the <strong>Project</strong> view onto the <strong>Cube</strong> GameObject in the <strong>Hierarchy</strong> view. Unity will automatically create a <strong>Script</strong> component on the <strong>Cube</strong> GameObject and assign the <strong>Rotation</strong> script asset as the script source for the component.</p>
<p>You should see something similar to what is shown in the image below.</p>
<div id="attachment_3457" class="wp-caption alignnone" style="width: 1050px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-My-Cube.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-My-Cube.png" alt="Unity - My Cube" title="Unity - My Cube" width="1040" height="784" class="size-full wp-image-3457" /></a><p class="wp-caption-text">Unity &#8211; My Cube</p></div>
<p>Notice in the <strong>Inspector</strong> view that the <strong>Cube</strong> GameObject now has the <strong>Rotation</strong> script component assigned to it.</p>
<p>If you play the game now, you should see something similar to what is shown below.</p>
<p><iframe src="http://3dgep.com/demos/RotatingCube/MyCube.html" scrolling="no" style="width:100%;min-height:380px"></iframe></p>
<span id="Adding_Your_Projects_to_Version_Control"><h1>Adding Your Projects to Version Control</h1></span>
<p>In this section I will discuss how to add your Unity project to a version control system (VCS). This is an optional step and is only required if you will be working together on the same project with other people or if you just want to save your project files in a version control repository for safe keeping.</p>
<p>I will not explain how to use the VCS. Whether you use Subversion, Git, Perforce, SourceSafe is not really important but knowing how to convert your project to use a Version Control System and what files need to be added to the VCS is important.</p>
<span id="Enable_Meta_File_Mode"><h2>Enable Meta File Mode</h2></span>
<p>The Unity Editor keeps track of the Assets (files) and the Asset import settings in the Asset database file. The asset database file is stored in the <strong>Library</strong> folder of the project Root.  It is generally not a good idea to distribute this file together with your project because the format of the file is platform specific (it may not be able to be opened properly on other OS&#8217;s other than the one it was created on).</p>
<p>To solve this problem, you can specify that you want to generate <strong>Meta Files</strong> for every single file, and directory in your project&#8217;s Asset folder.</p>
<p>To turn on <strong>Meta File Mode</strong> for your project, select &#8220;<strong>Edit -> Project Settings -> Editor</strong>&#8221; from the main menu.</p>
<div id="attachment_3460" class="wp-caption alignnone" style="width: 1050px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Edit-Project-Settings.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Edit-Project-Settings.png" alt="Unity - Edit Project Settings" title="Unity - Edit Project Settings" width="1040" height="784" class="size-full wp-image-3460" /></a><p class="wp-caption-text">Unity &#8211; Edit Project Settings</p></div>
<p>The <strong>Editor Settings</strong> will open in the <strong>Inspector</strong> view.</p>
<div id="attachment_3464" class="wp-caption alignnone" style="width: 1050px"><a href="http://3dgep.com/wp-content/uploads/2012/07/Unity-Enable-Meta-Files.png"><img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Enable-Meta-Files.png" alt="Unity - Enable Meta Files" title="Unity - Enable Meta Files" width="1040" height="784" class="size-full wp-image-3464" /></a><p class="wp-caption-text">Unity &#8211; Enable Meta Files</p></div>
<p>Select &#8220;<strong>Meta Files</strong>&#8221; in the <strong>Version Control Mode</strong> drop-down menu.</p>
<p>This will create a &#8220;.meta&#8221; file for every file and folder in your project&#8217;s Asset folder.</p>
<div class="my-note">
It is extremely important that if you copy/rename/move or delete a file or directory anywhere in the Assets folder that you also copy/rename/move or delete the .meta file with the same name. Failing to do this will break your project and all of your team members will become very angry with you!
</div>
<span id="Adding_to_Version_Control"><h2>Adding to Version Control</h2></span>
<p>Once you have enabled <strong>Meta File Mode</strong> on your project then you need to add the following folders to your version control system:</p>
<ul>
<li><strong>Assets</strong>: Add the <strong>Assets</strong> folder and every single file and corresponding <strong>.meta</strong> file in the <strong>Assets</strong> folder into your version control system.</li>
<li><strong>ProjectSettings</strong>: Add the <strong>ProjectSettings</strong> folder and all of its contents to your version control system.</li>
</ul>
<p>With the .meta files in place, Unity can rebuild the asset database and automatically re-import all of the raw assets in the Assets folder without losing references to files.</p>
<div class="my-note">
You do not need to commit the .sln (Visual Studio Solution files) or the .unityproj (MonoDevelop project files) as Unity is capable of regenerating these files based on the content of your Assets folder.
</div>
<span id="More_Information"><h1>More Information</h1></span>
<p>As a beginner, it may be difficult to get started with Unity because there is just so much to learn and there is so much information to absorb, you may not know where to begin.  The Unity website <a href="http://unity3d.com" title="Unity" target="_blank">http://unity3d.com</a> contains several links on the header but you will most likely want to see the documentation.</p>
<p>The main resource for Unity documentation is <a href="http://unity3d.com/support/documentation/" title="Unity Documentation" target="_blank">http://unity3d.com/support/documentation/</a>.</p>
<p>For a beginner, I recommend you first read the Basics: <a href="http://docs.unity3d.com/Documentation/Manual/UnityBasics.html" title="Unity Basics" target="_blank">http://docs.unity3d.com/Documentation/Manual/UnityBasics.html</a>.</p>
<p>With a good understanding of the basics, I recommend you watch a few video tutorials here: <a href="http://unity3d.com/support/documentation/video/" title="Video Tutorials" target="_blank">http://unity3d.com/support/documentation/video/</a> and then work through a few of the larger tutorials here: <a href="http://unity3d.com/support/resources/tutorials/" title="Unity Tutorials" target="_blank">http://unity3d.com/support/resources/tutorials/</a></p>
<p>While you are working on your projects, you will very often refer to the Unity Manual <a href="http://docs.unity3d.com/Documentation/Manual/index.html" title="Unity User Manual" target="_blank">http://docs.unity3d.com/Documentation/Manual/index.html</a>, the Reference Manual <a href="http://docs.unity3d.com/Documentation/Components/index.html" title="Reference Manual" target="_blank">http://docs.unity3d.com/Documentation/Components/index.html</a> and the Scripting Reference <a href="http://docs.unity3d.com/Documentation/ScriptReference/index.html" title="Scripting Reference" target="_blank">http://docs.unity3d.com/Documentation/ScriptReference/index.html</a>.</p>
<p>These three resources (<a href="http://docs.unity3d.com/Documentation/Manual/index.html" title="User Manual" target="_blank">User Manual</a>, <a href="http://docs.unity3d.com/Documentation/Components/index.html" title="Component Reference" target="_blank">Component Reference</a>, and <a href="http://docs.unity3d.com/Documentation/ScriptReference/index.html" title="Scripting Reference" target="_blank">Scripting Reference</a>) are also installed on your computer locally when you install Unity and are accessible from within the editor using the <strong>Help</strong> menu.</p>
<p>Additionally, you can click the <img src="http://3dgep.com/wp-content/uploads/2012/07/Unity-Component-Reference.png" alt="Component Reference" valign="middle" /> (Component Reference) button on any component in the <strong>Inspector</strong> view to go to that component&#8217;s reference documentation.</p>
<p>I wish you the best of luck creating that next block-buster title!</p>
]]></content:encoded>
			<wfw:commentRss>http://3dgep.com/?feed=rss2&#038;p=3246</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Page Caching using disk: basic
Database Caching using disk: basic
Object Caching 846/850 objects using disk: basic

 Served from: 3dgep.com @ 2013-05-25 17:47:34 by W3 Total Cache -->