<?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>Silent Kraken &#187; Programming</title>
	<atom:link href="http://www.blog.silentkraken.com/category/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.blog.silentkraken.com</link>
	<description>Game development for real</description>
	<lastBuildDate>Tue, 22 Jun 2010 21:35:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Manager systems for Unity3d, a new approach</title>
		<link>http://www.blog.silentkraken.com/2010/06/22/unity3d-manager-systems/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://www.blog.silentkraken.com/2010/06/22/unity3d-manager-systems/#comments</comments>
		<pubDate>Tue, 22 Jun 2010 21:35:24 +0000</pubDate>
		<dc:creator>sethillgard</dc:creator>
				<category><![CDATA[Game development]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[GameDev]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Tutorial]]></category>
		<category><![CDATA[Unity3d]]></category>

		<guid isPermaLink="false">http://www.blog.silentkraken.com/?p=173</guid>
		<description><![CDATA[Tutorial on how to create manager systems for Unity3d <a href="http://www.blog.silentkraken.com/2010/06/22/unity3d-manager-systems/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.blog.silentkraken.com%2F2010%2F06%2F22%2Funity3d-manager-systems%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.blog.silentkraken.com%2F2010%2F06%2F22%2Funity3d-manager-systems%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>As I said on a previous post, it is very common for Unity3d developers to come up with the idea of a game object in their scenes that will hold components that will act as <a href="http://en.wikipedia.org/wiki/Singleton_pattern">singletons</a>, right?</p>
<p>Normally we want this game object to be there from the beginning, make some initialization (such as finding entities in the scene) and then be ready to handle our requests. Also, we would like this game object to be persistent so we would like to call <em><a href="http://unity3d.com/support/documentation/ScriptReference/Object.DontDestroyOnLoad.html">DontDestoyOnLoad(this);</a></em> on it. This approach works very well if you have a single scene in your project as everything is running on the same context, but if you have multiple scenes, say, multiple levels in your game, things can get complicated. Suppose you have a component attached which purpose is to find the most used entities in your game (such as the player) and cache them, allowing other components to access them with a static variable. The problem with multiple scenes arises if you change scene and don&#8217;t update the references to your cached game objects.</p>
<p>I&#8217;ve using a slightly different approach that threats the whole system as a FSM (<a href="http://en.wikipedia.org/wiki/Finite-state_machine">Finite State Machine</a>). Let me exaplain:</p>
<p>The first idea is to create a static class that will hold a reference to any manager we have in the game, for example:</p>
<pre class="brush: csharp;">
[RequireComponent(typeof(GameManager))]
[RequireComponent(typeof(ScreenManager))]
[RequireComponent(typeof(AudioManager))]
[RequireComponent(typeof(MissionManager))]
public class Managers : MonoBehaviour
{
    private static GameManager gameManager;
    public static GameManager Game
    {
        get { return gameManager; }
    }

    private static ScreenManager screenManager;
    public static ScreenManager Screen
    {
        get { return screenManager; }
    }

    private static AudioManager audioManager;
    public static AudioManager Audio
    {
        get { return audioManager; }
    }

    private static MissionManager missionManager;
    public static MissionManager Mission
    {
        get { return missionManager; }
    }

	// Use this for initialization
	void Awake ()
    {
        //Find the references
        gameManager = GetComponent&amp;amp;lt;GameManager&amp;amp;gt;();
        screenManager = GetComponent&amp;amp;lt;ScreenManager&amp;amp;gt;();
        audioManager = GetComponent&amp;amp;lt;AudioManager&amp;amp;gt;();
        missionManager = GetComponent&amp;amp;lt;MissionManager&amp;amp;gt;();

        //Make this game object persistant
        DontDestroyOnLoad(gameObject);
	}
}
</pre>
<p>As you can see, we have a bunch of things that will let us access those Managers easily, as easy as:</p>
<pre class="brush: csharp;">Managers.Audio.Play(transform.position, clip); </pre>
<p>Obviously, those components (like the AudioManager) must be attached to this game object in order for this to work. The idea behind this managers is that they will be &#8220;always ready&#8221;, like a system service, and that they don&#8217;t have any dependencies with any particular scene. For example, the AudioManager is able to play sounds in any scene and situation.</p>
<p>There are other types of managers, those that rely on a particular scene or state in order to work. There is also the problem of the global game state. Introducing your awesome GameManager class:</p>
<pre class="brush: csharp;">
public class GameManager : MonoBehaviour
{
    private GameState currentState;
    public GameState State
    {
        get { return currentState; }
    }

	//Changes the current game state
	public void SetState(System.Type newStateType)
    {
        if (currentState != null)
        {
            currentState.OnDeactivate();
        }

        currentState = GetComponentInChildren(newStateType) as GameState;
        if (currentState != null)
        {
            currentState.OnActivate();
        }
	}

    void Update()
    {
        if (currentState != null)
        {
            currentState.OnUpdate();
        }
    }

    void Start()
    {
        SetState(typeof(GameplayState));
    }
}
</pre>
<p>And it&#8217;s loyal companion, the GameState abstract class:</p>
<pre class="brush: csharp;">
public abstract class GameState : MonoBehaviour
{
    public abstract void OnActivate();
    public abstract void OnDeactivate();
    public abstract void OnUpdate();
}
</pre>
<p>Those classes make up a simple FSM system for the different game states in your game (paused, playing, menu screen, etc.). You should inherit the GameState class to provide your custom states. A state is also a component attached to a game object that is responsible for activating/deactivating each game manager that is dependent on that particular state. For organization, I suggest you attach your states to game objects with the name of the state that are childs of the manager game object, like this:</p>
<div id="attachment_189" class="wp-caption aligncenter" style="width: 331px"><a href="http://www.blog.silentkraken.com/wp-content/uploads/2010/05/ManagersExample1.jpg#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed"><img class="size-full wp-image-189" title="Manager object distribution" src="http://www.blog.silentkraken.com/wp-content/uploads/2010/05/ManagersExample1.jpg" alt="Manager object distribution" width="321" height="93" /></a><p class="wp-caption-text">Manager object distribution</p></div>
<p>This way, you can have sub-managers attached to this child objects and everything is perfectly organized.</p>
<p>Hope you find this useful. I will post more information about this soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.silentkraken.com/2010/06/22/unity3d-manager-systems/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Simple AudioManager code for your Unity3d project</title>
		<link>http://www.blog.silentkraken.com/2010/04/06/audiomanager/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://www.blog.silentkraken.com/2010/04/06/audiomanager/#comments</comments>
		<pubDate>Wed, 07 Apr 2010 05:47:31 +0000</pubDate>
		<dc:creator>sethillgard</dc:creator>
				<category><![CDATA[Game development]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Audio]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[GameDev]]></category>
		<category><![CDATA[Release]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Unity3d]]></category>

		<guid isPermaLink="false">http://www.blog.silentkraken.com/?p=161</guid>
		<description><![CDATA[This is a simple component class that I created to help you play sounds in Unity3d. <a href="http://www.blog.silentkraken.com/2010/04/06/audiomanager/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.blog.silentkraken.com%2F2010%2F04%2F06%2Faudiomanager%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.blog.silentkraken.com%2F2010%2F04%2F06%2Faudiomanager%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>You know, sometimes very simple code has to be written again and again by lots of different people to solve the same basic problem. I think playing audio is one of such cases in Unity3d.</p>
<p>You have the audio components: <a href="http://unity3d.com/support/documentation/Components/class-AudioSource.html">AudioSource </a>(attached to your sound emitter) and <a href="http://unity3d.com/support/documentation/Components/class-AudioListener.html">AudioListener </a>(attached to the main camera). Now, the problem is that audio clips are represented by the <a href="http://unity3d.com/support/documentation/Components/class-AudioClip.html">AudioClip </a>class, and each AudioSource can have a single AudioClip playing at the moment. That is sometimes ok, but other times, you want your game object to be able to play a number of different sounds, maybe at the same time (Think of a character playing footsteps sounds and maybe saying something at the same time).</p>
<p>Since it is very natural to have one manager object in your scene acting as a <a href="http://en.wikipedia.org/wiki/Singleton_pattern">singleton</a>, I&#8217;ve written a component that can be attached to such manager. The work of this component is to play almost any sound you want to play in your game. The code is very simple and self explationary.</p>
<pre class="brush: csharp;">
// /////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Audio Manager.
//
// This code is release under the MIT licence. It is provided as-is and without any warranty.
//
// Developed by Daniel Rodríguez (Seth Illgard) in April 2010
// http://www.silentkraken.com
//
// /////////////////////////////////////////////////////////////////////////////////////////////////////////

using UnityEngine;
using System.Collections;

public class AudioManager : MonoBehaviour
{
    public AudioSource Play(AudioClip clip, Transform emitter)
    {
        return Play(clip, emitter, 1f, 1f);
    }

    public AudioSource Play(AudioClip clip, Transform emitter, float volume)
    {
        return Play(clip, emitter, volume, 1f);
    }

    /// &lt;summary&gt;
    /// Plays a sound by creating an empty game object with an AudioSource
    /// and attaching it to the given transform (so it moves with the transform). Destroys it after it finished playing.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;clip&quot;&gt;&lt;/param&gt;
    /// &lt;param name=&quot;emitter&quot;&gt;&lt;/param&gt;
    /// &lt;param name=&quot;volume&quot;&gt;&lt;/param&gt;
    /// &lt;param name=&quot;pitch&quot;&gt;&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    public AudioSource Play(AudioClip clip, Transform emitter, float volume, float pitch)
    {
        //Create an empty game object
        GameObject go = new GameObject (&quot;Audio: &quot; +  clip.name);
        go.transform.position = emitter.position;
        go.transform.parent = emitter;

        //Create the source
        AudioSource source = go.AddComponent&lt;AudioSource&gt;();
        source.clip = clip;
        source.volume = volume;
        source.pitch = pitch;
        source.Play ();
        Destroy (go, clip.length);
        return source;
    }

    public AudioSource Play(AudioClip clip, Vector3 point)
    {
        return Play(clip, point, 1f, 1f);
    }

    public AudioSource Play(AudioClip clip, Vector3 point, float volume)
    {
        return Play(clip, point, volume, 1f);
    }

    /// &lt;summary&gt;
    /// Plays a sound at the given point in space by creating an empty game object with an AudioSource
    /// in that place and destroys it after it finished playing.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;clip&quot;&gt;&lt;/param&gt;
    /// &lt;param name=&quot;point&quot;&gt;&lt;/param&gt;
    /// &lt;param name=&quot;volume&quot;&gt;&lt;/param&gt;
    /// &lt;param name=&quot;pitch&quot;&gt;&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    public AudioSource Play(AudioClip clip, Vector3 point, float volume, float pitch)
    {
        //Create an empty game object
        GameObject go = new GameObject(&quot;Audio: &quot; + clip.name);
        go.transform.position = point;

        //Create the source
        AudioSource source = go.AddComponent&lt;AudioSource&gt;();
        source.clip = clip;
        source.volume = volume;
        source.pitch = pitch;
        source.Play();
        Destroy(go, clip.length);
        return source;
    }
}
</pre>
<p>As you can see, this class is basically 6 overloads for the Play function. Basically we have two types: the type that takes a transform (emitter) as parameter and the type that takes a Vector3. The only difference is that if you provide a point (Vector3), the sound will be played there, but if you provide an emitter, the sound will be played where the emitter is, but will also follow the emitter as it moves (e.g. the engine of a passing car).<br />
Hope you find it useful!<br />
By the way, I&#8217;m planning on creating on tutorial on how to create Manager systems. By that I don&#8217;t mean simple components like this but rather the best way I have found to create such a Singleton object with those components, and how to integrate that with your game when you have multiple game states and game scenes (with potentially different managers). More on that soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.silentkraken.com/2010/04/06/audiomanager/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>TransformUtilities</title>
		<link>http://www.blog.silentkraken.com/2010/02/06/transformutilities/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://www.blog.silentkraken.com/2010/02/06/transformutilities/#comments</comments>
		<pubDate>Sun, 07 Feb 2010 03:36:02 +0000</pubDate>
		<dc:creator>sethillgard</dc:creator>
				<category><![CDATA[Game development]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[GameDev]]></category>
		<category><![CDATA[Release]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[Unity3d]]></category>

		<guid isPermaLink="false">http://www.blog.silentkraken.com/?p=121</guid>
		<description><![CDATA[Release of the TransformUtilities tools for Unity3d. <a href="http://www.blog.silentkraken.com/2010/02/06/transformutilities/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.blog.silentkraken.com%2F2010%2F02%2F06%2Ftransformutilities%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.blog.silentkraken.com%2F2010%2F02%2F06%2Ftransformutilities%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<div id="attachment_149" class="wp-caption alignright" style="width: 269px"><a href="http://www.blog.silentkraken.com/wp-content/uploads/2010/02/TransformUtilitiesWindow.jpg#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed"><img class="size-full wp-image-149 " title="TransformUtilitiesWindow" src="http://www.blog.silentkraken.com/wp-content/uploads/2010/02/TransformUtilitiesWindow.jpg" alt="" width="259" height="213" /></a><p class="wp-caption-text">This is how the tool looks like</p></div>
<p>Hello. I&#8217;ve been working on a set of four tools to aid in the Unity3d development. After using Unity for a while I encountered the classic problem of needing to copy the position of an object over and over. This led me to create the &#8220;Copy&#8221; tool. I&#8217;ve found a <a href="http://www.unifycommunity.com/wiki/index.php?title=CopyTransform">similar script</a> on the Unify community, but I wanted to extend the tool. It is now possible to copy position, rotation and scale of any axis you want. Also, the values apply to all objects selected in the scene.</p>
<p>After that, and inspired by the tools I found on the Gamebryo Lightspeed editor, I created the Randomize and Add Noise tools. Those tools work almost the same, the randomize the position, rotation of scale of any object selected (or all objects selected). The difference is that while Randomize sets the absolute values for position, rotation or scale, Add noise adds a delta to the current value of the transform. This is useful for example to randomize the Y rotation of all the trees in your level, or to make a bunch of boxes look more natural by not being perfectly aligned.</p>
<p>Finally, after been learning Autodesk 3ds Max, I created the Align tool inspired by a tool in that software. It basically takes a source transform, just like the Copy tool, then uses it&#8217;s collider and the collider of the object (or objects) selected to align it. You can align for example, the minimum point of your selection with the maximum point of your source (what you are aligning to) to place an object over another. It let&#8217;s you align using the minimum point, maximum point, the center of the object or the pivot point on both the selection and the source. You can align on all 3 axis.</p>
<p>To use these tool, all you need to do is download the script file, and add it into a folder named Editor in your project&#8217;s Asset folder. Once compiled by Unity you find the new functionality in Window -&gt; TransformUtilities, or simply press Ctrl+t (Cmd+t for Mac users)</p>
<p>Developed by Daniel Rodríguez (Seth Illgard) in January 2010</p>
<p><strong><a href="http://files.silentkraken.com/tools/unity3d/TransformUtilities/TransformUtilitiesWindow.cs">Download TransformUtilities!</a></strong></p>
<p>Hope you find them useful, and please let me know how can I improve theses tools.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.silentkraken.com/2010/02/06/transformutilities/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Coroutines in Unity3d (C# version)</title>
		<link>http://www.blog.silentkraken.com/2010/01/23/coroutines-in-unity3d-c-version/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://www.blog.silentkraken.com/2010/01/23/coroutines-in-unity3d-c-version/#comments</comments>
		<pubDate>Sun, 24 Jan 2010 00:04:15 +0000</pubDate>
		<dc:creator>sethillgard</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Coroutines]]></category>
		<category><![CDATA[GameDev]]></category>
		<category><![CDATA[Unity3d]]></category>

		<guid isPermaLink="false">http://www.blog.silentkraken.com/?p=106</guid>
		<description><![CDATA[Coroutines in C# work the same way that they do in Javascript (UnityScript), the only difference is that they require more typing (they have a slightly more complicated syntax). You should see the blog post on Javascript coroutines first. Here, &#8230; <a href="http://www.blog.silentkraken.com/2010/01/23/coroutines-in-unity3d-c-version/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.blog.silentkraken.com%2F2010%2F01%2F23%2Fcoroutines-in-unity3d-c-version%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.blog.silentkraken.com%2F2010%2F01%2F23%2Fcoroutines-in-unity3d-c-version%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>Coroutines in C# work the same way that they do in Javascript (UnityScript), the only difference is that they require more typing (they have a slightly more complicated syntax). You should see the <a href="http://www.blog.silentkraken.com/2010/01/22/coroutines-in-unity3d/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed">blog post on Javascript coroutines first</a>.</p>
<p>Here, I present the differences:</p>
<p><strong>Coroutines must have the <code>IEnumerator </code>return type:</strong></p>
<pre class="brush: csharp;">
IEnumerator MyCoroutine()
{
	//This is a coroutine
}
</pre>
<p><strong>To invoke a coroutine you must do it using the <code>StartCoroutine</code> method:</strong></p>
<pre class="brush: csharp;">
public class MyScript : MonoBehaviour
{
    void Start()
    {
		StartCoroutine(MyCoroutine());
    }

    IEnumerator MyCoroutine()
    {
        //This is a coroutine
    }
}
</pre>
<p><strong>The <code>yield</code> statement becomes <code>yield return</code> in C# :</strong></p>
<pre class="brush: csharp;">
IEnumerator MyCoroutine()
{
    DoSomething();
    yield return 0;	//Wait one frame, the 0 here is only because we need to return an IEnumerable
    DoSomethingElse();
}
</pre>
<p>Remember that we need to return an <code>IEnumerable</code>, so the Javascript <code>yield;</code> becomes <code>yield return 0;</code> in C#</p>
<p>Also, since C# requires you to use the <code>new</code> operator to create objects, if you want to use <code>WaitForSeconds </code> you have to use it like this:</p>
<pre class="brush: csharp;">
IEnumerator MyCoroutine()
{
    DoSomething();
    yield return new WaitForSeconds(2.0f);	//Wait 2 seconds
    DoSomethingElse();
}
</pre>
<p>Happy coroutining <img src='http://www.blog.silentkraken.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.silentkraken.com/2010/01/23/coroutines-in-unity3d-c-version/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Coroutines in Unity3d (Javascript version)</title>
		<link>http://www.blog.silentkraken.com/2010/01/22/coroutines-in-unity3d/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed</link>
		<comments>http://www.blog.silentkraken.com/2010/01/22/coroutines-in-unity3d/#comments</comments>
		<pubDate>Sat, 23 Jan 2010 03:23:42 +0000</pubDate>
		<dc:creator>sethillgard</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Coroutines]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Unity3d]]></category>

		<guid isPermaLink="false">http://www.blog.silentkraken.com/?p=80</guid>
		<description><![CDATA[The coroutine system in Unity3d hides a great power. Are you up to the task of discovering it? <a href="http://www.blog.silentkraken.com/2010/01/22/coroutines-in-unity3d/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fwww.blog.silentkraken.com%2F2010%2F01%2F22%2Fcoroutines-in-unity3d%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fwww.blog.silentkraken.com%2F2010%2F01%2F22%2Fcoroutines-in-unity3d%2F&amp;style=normal" height="61" width="50" /><br />
			</a>
		</div>
<p>I&#8217;ve been working with Unity3d for some time now and I couldn&#8217;t really make good use of the coroutines because I was unable to truly understand them. After some time playing with them and making some experiments I realized their true power. I couldn&#8217;t believe what I was missing! So, a couple of fellow game devs asked me to explain the concept to them. I decided that a blog post was the perfect way to do it and, at the same time, share this with everyone.</p>
<p><strong>Coroutines</strong>: Special type of functions(in the programming sense) that allows to stop it&#8217;s own execution until certain condition is met.</p>
<p>A coroutine looks like this (on javascript, the C# version is <a href="http://www.blog.silentkraken.com/2010/01/23/coroutines-in-unity3d-c-version/#utm_source=feed&amp;utm_medium=feed&amp;utm_campaign=feed">here</a>):</p>
<pre class="brush: jscript;">
function MyCoroutine()
{
	DoSomething():
	yield;                         //Mystery here
	DoSomethingElse();
}
</pre>
<p>When you invoke this function (start the coroutine) it will behave just like any other normal function you have ever seen, until it reaches the <strong>yield </strong>instruction.   The yield instruction explained:  The yield instruction works like a <strong>return </strong>statement in the sense that it stops the execution of the function and returns control to the code that invoked that function. The main difference is that the yield instruction lets you delay the execution of the code that is after it (in the last example, the DoSomethingElse() statement).</p>
<pre class="brush: jscript;">
function MyCoroutine()
{
	DoSomething():			//Do this immediately
	yield;                          //Return control to the caller
	DoSomethingElse();		//This will be executed one frame later
}

void Start()
{
	MyCoroutine();
}
</pre>
<p>What happens if you have more code after the MyCoroutine call? Let&#8217;s see an example with some prints:</p>
<pre class="brush: jscript;">
function MyCoroutine()
{
	print(&quot;This is printed second&quot;);
	yield;    	//Return control to the Start function
	print(&quot;This is printed one fourth, exactly one frame after the third&quot;);
}

void Start()
{
	print(&quot;This is printed first&quot;);
	MyCoroutine();
	print(&quot;This is printed third&quot;);
}
</pre>
<p>You can control when do the code after the yield instruction will be executed. It depends on the parameter of the yield instruction, according to the following table</p>
<p><strong>Nothing</strong>: It will wait one frame<br />
<strong>Another coroutine invocation</strong>: It will wait until the invoked coroutine finishes execution<br />
<strong>A WaitForSeconds object</strong>: It will wait certain amount of time</p>
<p>Confused? Here are the examples:</p>
<pre class="brush: jscript;">
function MyCoroutine()
{
	DoSomething():				//Do this immediately
	yield WaitForSeconds(2);   	//Return control to the caller
	DoSomethingElse();			//This will be executed 2 seconds after
}

void Start()
{
	MyCoroutine();
}
</pre>
<pre class="brush: jscript;">
function MyCoroutine()
{
	DoSomething():				//Do this immediately
	yield MyOtherCoroutine();   //Go and execute MyOtherCoroutine!
	DoSomethingElse();			//This will be executed after MyOtherCoroutine finished execution
}

function MyOtherCoroutine()
{
	DoStuff():				//Do this immediately
	yield WaitForSeconds(2);   	//Return control to the caller (in this case the Start function)
	DoMoreStuff();			//This will be executed 2 seconds after
	//MyOtherCoroutine finishes execution here
}

void Start()
{
	MyCoroutine();
}
</pre>
<p>As you can see, coroutines are very powerful and easy to use once you understand how they work. I will post some usage examples and the C# version of the scripts on this post soon.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.silentkraken.com/2010/01/22/coroutines-in-unity3d/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
