<?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>Horse Drawn Games</title>
	<atom:link href="https://www.horsedrawngames.com/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.horsedrawngames.com</link>
	<description>Horse Drawn Games</description>
	<lastBuildDate>Sun, 10 Jun 2018 09:50:52 +0000</lastBuildDate>
	<language>en-US</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	
	<item>
		<title>Type-safe object pool for Unity</title>
		<link>https://www.horsedrawngames.com/type-safe-object-pool-for-unity/</link>
		<comments>https://www.horsedrawngames.com/type-safe-object-pool-for-unity/#comments</comments>
		<pubDate>Sat, 09 Jun 2018 11:37:13 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=278</guid>
		<description><![CDATA[Managing memory usage can be crucial for decent performance in game development, especially on memory-constrained devices like mobile phones or consoles. It&#8217;s usually best to allocate what you need up-front at startup or on level load rather than mid-game during a frame, because the default memory allocators can be slow at finding free memory blocks....  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/type-safe-object-pool-for-unity/" title="ReadType-safe object pool for Unity">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>Managing memory usage can be crucial for decent performance in game development, especially on memory-constrained devices like mobile phones or consoles. It&#8217;s usually best to allocate what you need up-front at startup or on level load rather than mid-game during a frame, because the default memory allocators can be slow at finding free memory blocks. Constructing objects can also be time consuming depending on the complexity of your classes.</p>
<p>In a garbage collected, managed language like C# you still have to worry about this. You don&#8217;t know when the garbage collector is going to clean up objects that are no longer referenced in order to reclaim unused memory. If you allocate objects regularly every frame that quickly become unused and unreferenced, you&#8217;ll probably cause regular hitches in your framerate. Also in Unity the <code>Instantiate</code> function call can take quite a bit of CPU time.</p>
<p>One technique we can use to avoid these issues is called &#8220;object pooling&#8221;. Let&#8217;s say you want to spawn a firework particle effect:</p>
<a href="http://www.horsedrawngames.com/2014/wp-content/uploads/2018/06/fx.gif"><img class="alignnone size-full wp-image-285 aligncenter" alt="fx" src="http://www.horsedrawngames.com/2014/wp-content/uploads/2018/06/fx.gif" width="218" height="200" /></a>
<p>Instead of instantiating the prefab whenever you need it, you could pre-instantiate a list of them and disable them. Then when you need to spawn a new firework, go through the list, find one that isn&#8217;t enabled, enable it, configure its position, and play it. When it finishes, disable it. This way you re-use firework effects instead of continually creating new objects and destroying them later.</p>
<h2>A First Attempt</h2>
<p>A first pass on a system like this might look as follows:</p>
<pre class="brush: cpp; title: ; notranslate">
using UnityEngine;
using System.Collections.Generic;

public class BasicObjectPool : MonoBehaviour
{
    // Prefab for this object pool
    public GameObject m_prefab;

    // Size of this object pool
    public int m_size;

    public void Awake()
    {
        // Instantiate the pooled objects and disable them.
        for (var i = 0; i &lt; m_size; i++)
        {
            var pooledObject = Instantiate(m_prefab, transform);
            pooledObject.gameObject.SetActive(false);
        }
    }

    // Returns an object from the pool. Returns null if there are no more
    // objects free in the pool.
    public GameObject Get()
    {
        if (transform.childCount == 0)
            return null;

        return transform.GetChild(0).gameObject;
    }

    // Returns an object to the pool.
    public void ReturnObject(GameObject pooledObject)
    {
        // Reparent the pooled object to us and disable it.
        var pooledObjectTransform = pooledObject.transform;
        pooledObjectTransform.parent = transform;
        pooledObjectTransform.localPosition = Vector3.zero;
        pooledObject.gameObject.SetActive(false);
    }
}
</pre>
<p>Note that our <code>Get</code> method returns null if there are no more objects in the pool. We could also dynamically increase the size of the pool here, but that defeats the purpose of pre-allocating the objects. It&#8217;s up to the code calling <code>Get</code> to check if no object is available and handle that situation. In practice you would pick a pool size that adequately covers the maximum number of objects you would like to have available at any one time. It&#8217;s not feasible to just keep spawning objects &#8211; you&#8217;ll run out of memory if you do!</p>
<p>This solution isn&#8217;t bad, but I have one big problem with it. The pool doesn&#8217;t know what type of component you&#8217;re pooling! This means that you have to do a <code>GetComponent</code> call every time you get an object out of the pool. It also means that there are no guarantees that the pool even HAS the component type you&#8217;re expecting; you can&#8217;t enforce it, so someone could mis-configure it in a prefab or a scene.</p>
<p>Can we do better? Yes! With generics!</p>
<h2>Generics</h2>
<p>Generics are a feature of the C# language. They let you design a class or write a method with a placeholder type, which means you can write classes or methods that work with any data type, and still remain type safe. Unity makes use of them, and in fact if you use Unity&#8217;s <code>GetComponent&lt;..&gt;()</code> methods you, are already using them yourself.</p>
<p>This line:</p>
<pre class="brush: cpp; title: ; notranslate">fooGameObject.GetComponent&lt;FooComponent&gt;()</pre>
<p>gets the MonoBehaviour of type <code>FooComponent</code> which is on <code>fooGameObject</code>. How can this work? The Unity developers don&#8217;t know anything about your <code>FooComponent</code>. This syntax with the angled brackets indicates that the <code>GetComponent</code> method is a generic method which can work with any type (actually, specifically any MonoBehaviour type). When you call the method and put your type in the angled brackets, you tell the compiler to automatically generate a version of <code>GetComponent</code> that knows specifically about your type.</p>
<p>For more detailed information about generics, check out this <a href="https://msdn.microsoft.com/en-us/library/ms379564%28v=vs.80%29.aspx" target="_blank">introduction</a> from Microsoft.</p>
<h2>Improved Implementation</h2>
<p>Let&#8217;s implement our object pool class using generics. First we need to define a generic version of the class that accepts a type name. We want to pool Unity components, so we&#8217;ll also add a constraint on the type which says that it <strong>must</strong> be a MonoBehaviour:</p>
<pre class="brush: cpp; title: ; notranslate">public class ObjectPool&lt;T&gt; : MonoBehaviour where T : MonoBehaviour</pre>
<p>The <code>where</code> keyword defines the constraint. There are several different <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters" target="_blank">types</a> of constraints we can specify. In our case we want the constraint that says &#8220;the type MUST derive from MonoBehaviour&#8221;.</p>
<p>Now that we have the class defined like this, we can use the generic type placeholder <code>T</code> anywhere that we want to refer to the type that the pool was created with:</p>
<pre class="brush: cpp; title: ; notranslate">
public class ObjectPool&lt;T&gt; : MonoBehaviour where T : MonoBehaviour
{
    // Prefab for this pool. The prefab must have a component of type T on it.
    public T m_prefab;

    // Size of this object pool
    public int m_size;

    // The list of free and used objects for tracking.
    // We use the generic collections so we can give them our type T.
    private List m_freeList;
    private List m_usedList;

    public void Awake()
    {
        m_freeList = new List(m_size);
        m_usedList = new List(m_size);

        // Instantiate the pooled objects and disable them.
        for (var i = 0; i &lt; m_size; i++)
        {
            var pooledObject = Instantiate(m_prefab, transform);
            pooledObject.gameObject.SetActive(false);
            m_freeList.Add(pooledObject);
        }
    }
}
</pre>
<p>Let&#8217;s now add two methods: one to get an object out of the pool and one to return an object back to the pool. Previously we passed GameObjects around because we didn&#8217;t know what type we would be dealing with. Now that we are using generics, we can use our placeholder <code>T</code>:</p>
<pre class="brush: cpp; title: ; notranslate">
public T Get()
{
    var numFree = m_freeList.Count;
    if (numFree == 0)
        return null;

    // Pull an object from the end of the free list.
    var pooledObject = m_freeList[numFree - 1];
    m_freeList.RemoveAt(numFree - 1);
    m_usedList.Add(pooledObject);
    return pooledObject;
}

// Returns an object to the pool. The object must have been created
// by this ObjectPool.
public void ReturnObject(T pooledObject)
{
    Debug.Assert(m_usedList.Contains(pooledObject));

    // Put the pooled object back in the free list.
    m_usedList.Remove(pooledObject);
    m_freeList.Add(pooledObject);

    // Reparent the pooled object to us, and disable it.
    var pooledObjectTransform = pooledObject.transform;
    pooledObjectTransform.parent = transform;
    pooledObjectTransform.localPosition = Vector3.zero;
    pooledObject.gameObject.SetActive(false);
}
</pre>
<p>And we&#8217;re done! You can see the <a href="https://github.com/samizzo/TypeSafeObjectPool/blob/master/Assets/Scripts/ObjectPool.cs" target="_blank">full class</a> over on github. Now, we can&#8217;t actually add this class to a GameObject yet. As it stands, the class is just a kind of template. It doesn&#8217;t really exist as any concrete code until we declare it somewhere with a concrete type.</p>
<p>Let&#8217;s assume that we have an <code>Explosion</code> MonoBehaviour which is on a prefab:</p>
<pre class="brush: cpp; title: ; notranslate">
public class Explosion : MonoBehaviour
{
    private ParticleSystem m_particleSystem;

    public bool IsAlive { get { return m_particleSystem.IsAlive(); } }

    public void Awake()
    {
        m_particleSystem = GetComponent&lt;ParticleSystem&gt;();
    }

    public void Spawn(Vector3 position)
    {
        gameObject.SetActive(true);
        gameObject.transform.position = position;
        m_particleSystem.Play();
    }
}
</pre>
<p>We want to create a pool of <code>Explosion</code> objects. To do this, we must define a new class which derives from <code>ObjectPool</code> with the <code>Explosion</code> as our type parameter:</p>
<pre class="brush: cpp; title: ; notranslate">
public class ExplosionPool : ObjectPool&lt;Explosion&gt;
{
}
</pre>
<p>And that&#8217;s it! You can now add <code>ExplosionPool</code> to a GameObject, and assign a prefab to it. The <code>ObjectPool</code>&#8216;s <code>m_prefab</code> field will appear in the inspector, and it will only allow you to drop an <code>Explosion</code> component on it. It&#8217;s strongly typed!</p>
<a href="http://www.horsedrawngames.com/2014/wp-content/uploads/2018/06/objectpool.png"><img class="aligncenter size-full wp-image-333" style="border: 1px solid black;" alt="objectpool" src="http://www.horsedrawngames.com/2014/wp-content/uploads/2018/06/objectpool.png" width="448" height="215" /></a>
<p>Now to spawn an explosion, you can do this:</p>
<pre class="brush: cpp; title: ; notranslate">
public void SpawnExplosion(Vector3 position)
{
    var explosion = m_explosionPool.Get();
    if (explosion == null)
    {
        // The pool is empty, so we can't spawn any more at the moment.
        return;
    }

    explosion.Spawn(position);
    m_activeExplosions.Add(explosion);
}
</pre>
<p>In the above example we also keep track of the active explosions so we can return them to the pool when they are finished:</p>
<pre class="brush: cpp; title: ; notranslate">
public void Update()
{
    for (var i = 0; i &lt; m_activeExplosions.Count - 1; i &gt;= 0; i--)
    {
        var explosion = m_activeExplosions[i];
        if (!explosion.IsAlive)
        {
            m_activeExplosions.RemoveAt(i);
            m_explosionPool.ReturnObject(explosion);
        }
    }
}
</pre>
<p>Over on github I have a <a href="https://github.com/samizzo/TypeSafeObjectPool" target="_blank">sample Unity project</a> that demonstrates both the non-type-safe and type-safe methods. It&#8217;s a simple project that fires some particles from a pool when you click in the game window.</p>
<p>Feel free to hit me up on <a href="https://twitter.com/BananaboySam" target="_blank">Twitter</a> if you have any questions, or leave a comment below!</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/type-safe-object-pool-for-unity/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Decoding iOS crash call stacks</title>
		<link>https://www.horsedrawngames.com/decoding-ios-crash-call-stacks/</link>
		<comments>https://www.horsedrawngames.com/decoding-ios-crash-call-stacks/#comments</comments>
		<pubDate>Wed, 05 Apr 2017 13:58:34 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=237</guid>
		<description><![CDATA[Wow it&#8217;s been a while since I updated the blog! I think we&#8217;re due for a web site refresh too. But first let&#8217;s talk about call stacks! Let&#8217;s say your iOS game crashes outside of the debugger. Assuming your device is plugged into your mac, you can get the device log from Xcode by bringing...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/decoding-ios-crash-call-stacks/" title="ReadDecoding iOS crash call stacks">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>Wow it&#8217;s been a while since I updated the blog! I think we&#8217;re due for a web site refresh too. But first let&#8217;s talk about call stacks!</p>
<p>Let&#8217;s say your iOS game crashes outside of the debugger. Assuming your device is plugged into your mac, you can get the device log from Xcode by bringing up the &#8220;Devices&#8221; window via Window -> Devices. You should see a live updated log and you might be able to find your crash details in among the spammy output. But even better &#8211; if you click on &#8220;View Device Logs&#8221; you&#8217;ll see a list of apps that have crashed.</p>
<a href="https://www.horsedrawngames.com/2014/wp-content/uploads/2017/04/Screen-Shot-2017-04-05-at-10.53.50-PM.png"><img src="https://www.horsedrawngames.com/2014/wp-content/uploads/2017/04/Screen-Shot-2017-04-05-at-10.53.50-PM.png" alt="Screen Shot 2017-04-05 at 10.53.50 PM" width="1238" height="838" class="alignnone size-full wp-image-257" /></a>
<p>In this example, <a href="https://www.polyphoniclp.com/resynth" title="Resynth" target="_blank">Resynth</a> (a game I&#8217;ve been working on for my new company <a href="https://www.polyphoniclp.com" title="Polyphonic LP" target="_blank">Polyphonic LP</a>) has crashed a couple of times, and I&#8217;ve selected one of the crashes.</p>
<p>Why did it crash? Luckily we have the full call stack. A call stack is simply a list of functions that are currently being executed by the CPU. In this case, the call stack looks like this:</p>
<pre class="brush: cpp; title: ; notranslate">
Thread 0 Crashed:
0   libobjc.A.dylib               	0x000000018749ef68 objc_msgSend + 8
1   Foundation                    	0x0000000189548ba4 _NS_os_log_callback + 68
2   libsystem_trace.dylib         	0x0000000187b0f954 _NSCF2data + 112
3   libsystem_trace.dylib         	0x0000000187b0f564 _os_log_encode_arg + 736
4   libsystem_trace.dylib         	0x0000000187b0ffb8 _os_log_encode + 1036
5   libsystem_trace.dylib         	0x0000000187b13200 os_log_with_args + 892
6   libsystem_trace.dylib         	0x0000000187b1349c os_log_shim_with_CFString + 172
7   CoreFoundation                	0x0000000188a38de4 _CFLogvEx3 + 152
8   Foundation                    	0x0000000189549cb0 _NSLogv + 132
9   resynth                       	0x000000010056ac28 0x10004c000 + 5368872
10  resynth                       	0x000000010056b654 0x10004c000 + 5371476
11  resynth                       	0x000000010056bdd4 0x10004c000 + 5373396
12  resynth                       	0x00000001000b13f4 0x10004c000 + 414708
13  resynth                       	0x0000000100081c94 0x10004c000 + 220308
14  resynth                       	0x00000001000816f4 0x10004c000 + 218868
15  resynth                       	0x000000010053a33c 0x10004c000 + 5169980
16  resynth                       	0x0000000100e23404 0x10004c000 + 14513156
17  resynth                       	0x0000000100714b54 0x10004c000 + 7113556
18  resynth                       	0x0000000100714f24 0x10004c000 + 7114532
19  resynth                       	0x0000000100708054 0x10004c000 + 7061588
20  resynth                       	0x0000000100709db4 0x10004c000 + 7069108
21  resynth                       	0x000000010070a0a8 0x10004c000 + 7069864
</pre>
<p>There isn&#8217;t much symbol information; the only thing we can really see is that the <code>NSLog</code> function was running. But what called <code>NSLog</code> and what caused it to crash?</p>
<p>Fortunately there are several tools we can use to decode this. I&#8217;m going to cover one of them today: <code>atos</code>. <code>atos</code> converts memory addresses to symbol names, and it comes with macOS and lives in <code>/usr/bin</code> so it should already be in your path. It takes a couple of parameters:</p>
<p><code>atos -arch &lt;architecture&gt; -l &lt;load address&gt; -o &lt;path to debug binary&gt; &lt;addresses&gt;</code></p>
<p>We need to supply the architecture of our binary, the load address (the base address in memory where the executable was loaded), the path to a version of our binary with full debug information present, and the list of call stack addresses that we wish to translate into symbols.</p>
<p>If you have archived your game from Xcode, the full debug executable can be found inside the archive, in <code>dSYMs/resynth.app.dSYM/Contents/Resources/DWARF</code>.</p>
<p>Our architecture is <code>arm64</code> (unless you&#8217;re running <code>arm7</code> which is unlikely these days).</p>
<p>For this crash our load address is <code>0x10004c000</code>. The load address could be anything and won&#8217;t always be the same. Sometimes the load address might not be present, and the call stack lines might look something like this:</p>
<pre class="brush: cpp; title: ; notranslate">9   resynth                       	0x000000010056ac28 resynth + 5368872</pre>
<p>This can happen if you get your crash information from the device log view in Xcode instead of from the specific application crash view.</p>
<p>Here <code>0x000000010056ac28</code> is the real memory address where this particular function was loaded, and <code>5368872</code> is the offset of the function from the load address. We can therefore easily calculate the load address; it&#8217;s just <code>0x000000010056ac28 - 5368872</code> which is <code>0x10004C000</code>.</p>
<p>Now we have everything we need, so let&#8217;s run this!</p>
<pre class="brush: cpp; title: ; notranslate">
$ atos -arch arm64 -l 0x10004c000 -o resynth-debug 0x000000010056ac28 0x000000010056b654 0x000000010056bdd4
CM_NSLog(NSString*, ...) (in resynth-debug) (CloudManager.mm:17)
-[CloudManager getLongLong:] (in resynth-debug) (CloudManager.mm:171)
getLongLong (in resynth-debug) (CloudManager.mm:225)
</pre>
<p>In the interests of brevity I&#8217;ve used only the three top most addresses. This is usually enough to figure out the problem anyway!</p>
<p>In this case the culprit turns out to be the <code>getLongLong</code> Objective-C method:</p>
<pre class="brush: cpp; title: ; notranslate">
- (long long) getLongLong:(NSString *)key
{
    NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
    long long value = [[userDefaults objectForKey:key] longLongValue];
    DEBUG(@&quot;CloudManager: getLongLong key=%@ value=%@&quot;, key, value);
    return value;
}
</pre>
<p>On line 5 we specify a string with the <code>%@</code> format specifier, which means we should be passing in an <code>NSObject</code>-derived object. However, we are instead passing a <code>long long</code> value which causes a crash.</p>
<p>The fix is simple. We just convert the <code>long long</code> to an <code>NSObject</code>:</p>
<pre class="brush: cpp; title: ; notranslate">DEBUG(@&quot;CloudManager: getLongLong key=%@ value=%@&quot;, key, @(value));</pre>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/decoding-ios-crash-call-stacks/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Hdg Remote Debug &#8211; Released!</title>
		<link>https://www.horsedrawngames.com/hdg-remote-debug-released/</link>
		<comments>https://www.horsedrawngames.com/hdg-remote-debug-released/#comments</comments>
		<pubDate>Fri, 13 May 2016 09:00:42 +0000</pubDate>
		<dc:creator><![CDATA[Geoff]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Remote Debug Tool]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=230</guid>
		<description><![CDATA[You can now get the Remote Debug tool on the asset store! Editing live on the device has never been easier, for fast iteration time and the ultimate in &#8220;what you see is what you get&#8221;.  For more info check out this video, the forum thread or just read some of the other entries on this...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/hdg-remote-debug-released/" title="ReadHdg Remote Debug &#8211; Released!">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>You can now get the Remote Debug tool on the <a title="asset store" href="https://www.assetstore.unity3d.com/en/#!/content/61863">asset store</a>!</p>
<p>Editing live on the device has never been easier, for fast iteration time and the ultimate in &#8220;what you see is what you get&#8221;.  For more info check out this <a title="video" href="https://www.youtube.com/watch?v=3Oigkg-8rWQ">video</a>, the <a title="forum thread" href="http://forum.unity3d.com/threads/hdg-remote-debug-live-update-inspector-for-your-phone.399096/">forum thread</a> or just read some of the other entries on this blog!</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/hdg-remote-debug-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Hdg Remote Debug &#8211; How It Works</title>
		<link>https://www.horsedrawngames.com/hdg-remote-debug-more-info/</link>
		<comments>https://www.horsedrawngames.com/hdg-remote-debug-more-info/#comments</comments>
		<pubDate>Tue, 03 May 2016 01:06:49 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Remote Debug Tool]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[network]]></category>
		<category><![CDATA[remote]]></category>
		<category><![CDATA[unity3d]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=220</guid>
		<description><![CDATA[Hdg Remote Debug works using .NET&#8217;s reflection features; it doesn&#8217;t use any sort of built-in Unity serialisation. Every second it gathers all GameObjects that are currently active, finds all Components on them, and for each component, uses reflection to find all serialised and public fields. This data is sent back to the client running in...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/hdg-remote-debug-more-info/" title="ReadHdg Remote Debug &#8211; How It Works">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>Hdg Remote Debug works using .NET&#8217;s reflection features; it doesn&#8217;t use any sort of built-in Unity serialisation. Every second it gathers all <code>GameObjects</code> that are currently active, finds all <code>Components</code> on them, and for each component, uses reflection to find all serialised and public fields. This data is sent back to the client running in the editor over a network connection, where the data is displayed in custom hierarchy and inspector windows.</p>
<p>This means it doesn&#8217;t use the built-in Unity inspectors or any custom inspectors you may have created, so when you click on, say, a <code>Camera</code> object you see the public and serialised fields of the <code>Camera</code> type rather than what Unity&#8217;s built-in <code>CameraEditor</code> inspector would have shown.</p>
<p>I would like to fix this and use the built-in inspectors and I have actually prototyped it extensively but it turns out there are several problems. To use the built-in inspectors we require a proxy <code>GameObject</code> that represents the selected object on the server. The idea is that whenever we receive a message from the server, we create a new proxy <code>GameObject</code>, dynamically add all components to it, and for each component, create an <code>Editor</code> instance with <code>Editor.CreateEditor(component)</code>. When drawing the UI for the components, we just call <code>Editor.OnInspectorGUI</code> for each one and use <code>BeginChangeCheck/EndChangeCheck</code> to determine if anything changed. If fields have changed we send a message to the server to update it.</p>
<p>There are a couple of problems with this approach. The built-in inspectors cause undo events to be added to the system, but those undo events are undesirable; the <code>GameObject</code> is a temporary proxy object for which we don&#8217;t want to track undo events. In fact the object is not visible in the scene, so the undo events seem spurious to the user. It&#8217;s not a good user experience to generate all these undo events that go nowhere.</p>
<p>Another problem is that <code>EndChangeCheck</code> doesn&#8217;t detect that changes have happened when certain fields are changed. One such field that I found was the camera mask property. It seems to be something to do with the <code>EditorGUI.PropertyField</code>, which doesn&#8217;t seem to set <code>GUI.changed</code> to true.</p>
<p>The last major problem is with the proxy <code>GameObject</code>. We create a new proxy every time we receive a message from the server, but destroying the previous one seems to cause the <code>Editor</code> objects that we created to throw <code>NullReferenceExceptions</code> when you hit play or when Unity reloads assemblies, when it tries to reinitialise its <code>serializedObject</code> field. I think I need to find a way to clear the reference on the <code>Editor</code> when destroying the <code>GameObject</code>, but it wasn&#8217;t possible when I last investigated. I can&#8217;t just leave the proxy object; that&#8217;s a memory leak!</p>
<p>I have a Trello <a href="https://trello.com/b/TSDsEbrA/hdg-remote-debug-roadmap" target="_blank">roadmap board</a> with some features I&#8217;d like to add. Some are wishlist features which may not really be possible without digging into the Unity source (e.g. hotswapping prefabs, or the aforementioned built-in inspectors). One feature I would like to add is an extensible console system, where you can hook in your own commands to control the game remotely. That way you can add debug features to the game that you can then control from Unity.</p>
<p>Get in touch if you have any questions or feature requests for Hdg Remote Debug!</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/hdg-remote-debug-more-info/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Remote debug / live update of Unity builds on device</title>
		<link>https://www.horsedrawngames.com/remote-debug-live-update-of-unity-builds-on-device/</link>
		<comments>https://www.horsedrawngames.com/remote-debug-live-update-of-unity-builds-on-device/#comments</comments>
		<pubDate>Sat, 30 Apr 2016 12:09:43 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Remote Debug Tool]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[remote]]></category>
		<category><![CDATA[unity3d]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=214</guid>
		<description><![CDATA[Unity has a feature called the Unity Remote which is an app that you run on an Android or iOS device. The editor talks to this app via USB and sends the render output of the game as it is running in the editor to the device. The touch inputs from the device along with...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/remote-debug-live-update-of-unity-builds-on-device/" title="ReadRemote debug / live update of Unity builds on device">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>Unity has a feature called the <a title="Unity Remote" href="http://docs.unity3d.com/Manual/UnityRemote4.html" target="_blank">Unity Remote</a> which is an app that you run on an Android or iOS device. The editor talks to this app via USB and sends the render output of the game as it is running in the editor to the device. The touch inputs from the device along with other device-specific data such as GPS and accelerometer are also sent back to the editor. This gives you an idea of how your game looks on a device and also lets you test touch controls and other device hardware without having to constantly do full builds.</p>
<p>That&#8217;s the theory, anyway. A lot of people have complaints about the Unity Remote, saying that it doesn&#8217;t work very well or at all.</p>
<p>I&#8217;ve always felt that Unity should have a live debug view of the game running on the device that shows you all the GameObjects and their components and serialised fields. I imagined it would look like the regular built-in hierarchy and inspector windows, except it would be pulling the data via a network connection from the live build. A lot of AAA engines have a live update feature like this but Unity has nothing.</p>
<p>In 2014 I started work on a tool to do just this. I built an initial prototype with plans to sell it on the asset store. But then contracting jobs got in the way, and I put the project on hold. Late last year my contract work dried up, and I decided it was time to get back to it and finish it off, so I&#8217;ve spent the last four months working on it. It&#8217;s now working pretty well:</p>
<p>&nbsp;</p>
<p>You can sit in Unity, bring up the Remote Debug window, connect to your device, and see what&#8217;s happening on it, just as though you were looking at a build running in the editor. It&#8217;s really easy to iterate on things on the device, and I&#8217;ve found it especially useful for tweaking touch controls.</p>
<p>Currently it requires Unity 5.3.2f1 or better because I&#8217;m using the new <a href="https://docs.unity3d.com/ScriptReference/SceneManagement.Scene.GetRootGameObjects.html" target="_blank"><code>Scene.GetRootGameObjects</code></a> API that was added. I can make it work in previous versions of Unity but with some unfortunate side effects depending on what API I use. If I use <code>Object.FindObjectsOfType</code> I can&#8217;t get inactive objects. There is also <code>Resources.FindObjectsOfType</code> but it returns all objects including resources that were manually loaded from the Resources directory. I think I can filter these out, but it just means the server is a bit more costly in terms of memory and CPU. This is something I want to do though because it would be great to provide versions of the tool for Unity 5.x across the board.</p>
<p>I&#8217;ve made a thread on the <a href="http://forum.unity3d.com/threads/hdg-remote-debug-live-update-inspector-for-your-phone.399096/" target="_blank">Unity forums</a> about Hdg Remote Debug. If you want more information feel free to post there or email us here at Horse Drawn HQ. The tool should be going live on the asset store in the next couple of weeks.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/remote-debug-live-update-of-unity-builds-on-device/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Visual Studio shader syntax highlighting part 2</title>
		<link>https://www.horsedrawngames.com/shader-syntax-highlighting/</link>
		<comments>https://www.horsedrawngames.com/shader-syntax-highlighting/#comments</comments>
		<pubDate>Tue, 23 Feb 2016 05:11:53 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[cg]]></category>
		<category><![CDATA[glsl]]></category>
		<category><![CDATA[hlsl]]></category>
		<category><![CDATA[shaders]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=191</guid>
		<description><![CDATA[I have updated the NShader syntax highlighter to allow adding extra extensions dynamically via the Visual Studio settings. This is one of the most requested features, and it really is a feature that makes sense. The plugin was previously hard-coded to specific file extensions. The reason for this is because that&#8217;s just the way you...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/shader-syntax-highlighting/" title="ReadVisual Studio shader syntax highlighting part 2">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>I have updated the NShader syntax highlighter to allow adding extra extensions dynamically via the Visual Studio settings. This is one of the most requested features, and it really is a feature that makes sense. The plugin was previously hard-coded to specific file extensions. The reason for this is because that&#8217;s just the way you define what file extensions your language service is for in a Visual Studio plugin; you add a bunch of attributes to your <code>Package</code> implementation.</p>
<p>However if you implement the <code>IVsEditorFactory</code> interface, you can get an entry to show up in the VS settings page! You don&#8217;t even have to implement the full interface yourself because there is a built-in implementation that does most of the hard work called <code><a href="https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.package.editorfactory.aspx">EditorFactory</a></code>.</p>
<p>To use this updated version, in Tools->Options->Text Editor->File Extension, add a file extension, select &#8220;NShader Editor&#8221; in the dropdown, and click &#8220;Add&#8221;. Then when you open a file with any of those extensions they will use the NShader syntax highlighter. Files will default to using the HLSL highlighter, so if you want to force them to use GLSL, CG, or Unity, you can use the <code>shadertype</code> tag I mentioned in my <a href="http://www.horsedrawngames.com/shader-syntax-highlighting-in-visual-studio-2013/" title="previous">previous</a> post.</p>
<p>Note that all the file extensions that NShader previously recognised are still recognised, so if you are using any of those file types you don&#8217;t have to do anything extra.</p>
<p>It seems that there is a bug in at least Visual Studio 2013 and possibly earlier versions where the setting can be forgotten and when you open a file in the list the syntax highlighting is not applied. However, the extension still appears in the list. To work around this you must remove and re-add the extension to the list. Also in Visual Studio 2015 if you load a file from the &#8220;recently used&#8221; list it doesn&#8217;t seem to use the syntax highlighter, but if you load it from elsewhere (e.g. File->Open or the Solution Explorer) it will work. This seems like a bug in Visual Studio, because it worked in 2013.</p>
<p>If you add a file extension or use the <code>shadertype</code> tag you will need to close and re-open any currently open files to reflect the changes.</p>
<p>An installer for NShader can be downloaded <a href="https://github.com/samizzo/nshader/releases/download/2.0/NShader.vsix">here</a>. The installer can be used to install into both Visual Studio 2013 and 2015.</p>
<p>The source code is available on github <a href="https://github.com/samizzo/nshader">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/shader-syntax-highlighting/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Ring buffers / circular buffers</title>
		<link>https://www.horsedrawngames.com/ring-buffers-circular-buffers/</link>
		<comments>https://www.horsedrawngames.com/ring-buffers-circular-buffers/#comments</comments>
		<pubDate>Mon, 08 Feb 2016 00:59:33 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[c#]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=118</guid>
		<description><![CDATA[A ring buffer, also known as a circular buffer or cyclic buffer, is a very useful data structure for certain situations, and worth having around in your programmer&#8217;s toolchest. It&#8217;s a fixed-size buffer but treated as though it&#8217;s connected end to end (that is, the end is connected to the start) and data is written...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/ring-buffers-circular-buffers/" title="ReadRing buffers / circular buffers">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>A <a title="ring buffer" href="https://en.wikipedia.org/wiki/Circular_buffer">ring buffer</a>, also known as a circular buffer or cyclic buffer, is a very useful data structure for certain situations, and worth having around in your programmer&#8217;s toolchest. It&#8217;s a fixed-size buffer but treated as though it&#8217;s connected end to end (that is, the end is connected to the start) and data is written and read in a FIFO (first-in first-out) way. Usually this is all hidden behind an API to make it easy to read and write to it.</p>
<p>They are often used when there is a need to read and write data in a streaming manner, for example, streaming audio to a sound card, I/O buffering for a UART in an embedded device, and in fact any I/O buffer situation (e.g. a network device or a disk). Because the buffer is fixed in size you know what the memory footprint will be up front and this makes it ideal for use in embedded systems or on consoles where memory is constrained and you don&#8217;t want to dynamically allocate memory.</p>
<h2>Overview</h2>
<p>You can imagine a ring buffer as a circular block of memory that cycles around like this (the numbers represent the indices into the block of memory, which is treated as an array of bytes):</p>
<p style="text-align: center;"><img class="size-full wp-image-122 aligncenter" alt="ringbuffer1" src="https://www.horsedrawngames.com/2014/wp-content/uploads/2016/02/ringbuffer1.png" width="256" height="256" /></p>
<h6 style="text-align: center;">Fig. 1 &#8211; Imaginary ring buffer</h6>
<p>But of course in reality the memory is really laid out like this:</p>
<p style="text-align: center;"><img class="size-full wp-image-129 aligncenter" alt="ringbuffer2" src="https://www.horsedrawngames.com/2014/wp-content/uploads/2016/02/ringbuffer2.png" width="512" height="81" /></p>
<h6 style="text-align: center;">Fig. 2 &#8211; Actual memory layout</h6>
<p>The current read and write locations in the buffer are tracked, and the ring buffer operation is as follows:</p>
<ul>
<li><span style="line-height: 1.5em;">When writing, we copy new data into the buffer starting at the write location, and if the new data goes off the end of the buffer, we wrap around and write the remaining data starting at the start of the buffer, until we have written all data or we run out of space.</span></li>
<li><span style="line-height: 1.5em;">When reading, we copy data out of the buffer starting at the read location until we have read some specified amount of data, or we reach the write location, wrapping around the end of the buffer as above.</span></li>
</ul>
<p>We know we&#8217;ve run out of space for writing when we reach the read location, and we know we have no more data to read when we reach the write location. In those cases we can just stop and return the amount of data actually written or read.</p>
<h2>Implementation</h2>
<p>Phew! That seems complicated! Let&#8217;s break this down and look at how we might implement it. We need to keep track of a few things:</p>
<ul>
<li>A pointer to the start of the memory for the buffer.</li>
<li>The size of the buffer in bytes.</li>
<li>The current read index in the buffer.</li>
<li>The current write index in the buffer.</li>
</ul>
<p>The read and write indices represent where the current read and write location is in the buffer (these could instead be kept as pointers if we wanted).</p>
<p>In my implementation I also choose to track:</p>
<ul>
<li>The number of bytes available for reading.</li>
<li>The number of bytes available for writing.</li>
</ul>
<p>We can actually avoid tracking these two if we want, but it makes everything a bit clearer and doesn&#8217;t cost us much more.</p>
<p>We also want to be able to read and write to the buffer. Let&#8217;s sketch out a class for what we have so far:</p>
<pre class="brush: cpp; title: ; notranslate">
class RingBuffer
{
    public:
        RingBuffer(int sizeBytes);
        ~RingBuffer();

        // Copies 'length' bytes from 'source' to the ring buffer.
        // Returns the number of bytes actually written, which may be less than 'length'
        // if there was insufficient space to write into the ring buffer.
        int Write(const void* source, int length);

        // Reads 'length' bytes from the ring buffer into 'dest'.
        // Returns the number of bytes actually read, which may be less than 'length'
        // if there was insufficient data in the ring buffer.
        int Read(void* dest, int length);

    private:
        char* m_buffer;
        int m_sizeBytes;
        int m_readIndex;
        int m_writeIndex;
        int m_readBytesAvailable;
        int m_writeBytesAvailable;
}
</pre>
<p>For our write function we&#8217;ll clamp the length to the amount of space available for writing, and for our read function we&#8217;ll clamp it to the amount of data available in the buffer for reading.</p>
<h2>Reading and Writing</h2>
<p>We have two possible situations we need to handle when implementing reading and writing. The case where the current write index is greater than the current read index:</p>
<p style="text-align: center;"><img class="size-full wp-image-132 aligncenter" alt="ringbuffer3" src="https://www.horsedrawngames.com/2014/wp-content/uploads/2016/02/ringbuffer3.png" width="512" height="128" /></p>
<h6 style="text-align: center;">Fig. 3 &#8211; Write index greater than read index</h6>
<p>And the case where the current write index is less than the current read index:</p>
<p style="text-align: center;"><img class="size-full wp-image-143 aligncenter" alt="ringbuffer4" src="https://www.horsedrawngames.com/2014/wp-content/uploads/2016/02/ringbuffer4.png" width="512" height="128" /></p>
<h6 style="text-align: center;">Fig. 4 &#8211; Write index less than read index</h6>
<p>For writing in figure 3, we need to split the write up into two regions. The first region is from the current write index to the end of the buffer (index 11 to 15 inclusive), and the second region is from the start of the buffer to just before the current read index (index 0 to 3 inclusive):</p>
<p style="text-align: center;"><a href="https://www.horsedrawngames.com/2014/wp-content/uploads/2016/02/ringbuffer5.png"><img class="size-full wp-image-160 aligncenter" alt="ringbuffer5" src="https://www.horsedrawngames.com/2014/wp-content/uploads/2016/02/ringbuffer5.png" width="512" height="128" /></a></p>
<h6 style="text-align: center;">Fig. 5 &#8211; Two regions for writing</h6>
<p>For the figure 4 case, we have just one region, from the current write index to just before the current read index (index 1 to 8 inclusive):</p>
<p style="text-align: center;"><a href="https://www.horsedrawngames.com/2014/wp-content/uploads/2016/02/ringbuffer6.png"><img class="aligncenter size-full wp-image-161" alt="ringbuffer6" src="https://www.horsedrawngames.com/2014/wp-content/uploads/2016/02/ringbuffer6.png" width="512" height="128" /></a></p>
<h6 style="text-align: center;">Fig. 6 &#8211; One region for writing</h6>
<p>Reading is pretty much the same, but opposite! For reading in the figure 3 case, we just read from the current read index to just before the current write index (index 4 to 10 inclusive). For the figure 4 case we need to split the read up into two regions. The first region is from the current read index to the end of the buffer (index 9 to 15 inclusive), and the second region is from the start of the buffer to just before the current write index (index 0 only).</p>
<p>When there are two regions, it&#8217;s possible that the length of data we want to write or read isn&#8217;t enough to take us into the second region! So we may only end up requiring one region. Clamping the length makes it easy to determine this without a whole lot of nested if statements, because we can compare the clamped length to the remaining bytes in the buffer from the current read or write index. I think this is easier to explain in code, so putting this all together, we can come up with a write function like this:</p>
<pre class="brush: cpp; title: ; notranslate">
int RingBuffer::Write(const void* source, int length)
{
    assert(m_buffer);
    assert(source);
    assert(length &gt;= 0);
    assert(m_writeBytesAvailable &gt;= 0);

    // If there is no space or nothing to write then don't do anything.
    if (m_writeBytesAvailable == 0 || length == 0)
        return 0;

    // Clamp the length to the number of bytes available for writing.
    if (length &gt; m_writeBytesAvailable)
        length = m_writeBytesAvailable;

    int remainingWriteBytes = m_sizeBytes - m_writeIndex;
    if (length &gt; remainingWriteBytes)
    {
        // If the number of bytes to write is bigger than the remaining bytes
        // in the buffer, we have to wrap around and write into two regions.
        memcpy(m_buffer + m_writeIndex, source, remainingWriteBytes);
        memcpy(m_buffer, (char*)source + remainingWriteBytes, length - remainingWriteBytes);
    }
    else
    {
        // No wrapping, only one region to write to, which starts from the write index.
        memcpy(m_buffer + m_writeIndex, source, length);
    }

    // Increment the write index and wrap around at the end.
    m_writeIndex = (m_writeIndex + length) % m_sizeBytes;

    // Update the read and write sizes.
    m_writeBytesAvailable -= length;
    m_readBytesAvailable += length;

    return length;
}
</pre>
<p>Our read function will look pretty similar:</p>
<pre class="brush: cpp; title: ; notranslate">
int RingBuffer::Read(void* dest, int length)
{
    assert(m_buffer);
    assert(dest);
    assert(length &gt;= 0);
    assert(m_readBytesAvailable &gt;= 0);

    // If there is no data in the buffer or nothing to read then don't do anything.
    if (IsEmpty() || length == 0)
        return 0;

    // Clamp the length to the maximum number of bytes available for reading.
    if (length &gt; m_readBytesAvailable)
        length = m_readBytesAvailable;

    int remainingReadBytes = m_sizeBytes - m_readIndex;
    if (length &gt; remainingReadBytes)
    {
        // If the number of bytes to read is bigger than the remaining bytes
        // in the buffer, we have to wrap around and read from two regions.
        memcpy(dest, m_buffer + m_readIndex, remainingReadBytes);
        memcpy((char*)dest + remainingReadBytes, m_buffer, length - remainingReadBytes);
    }
    else
    {
        // No wrapping, only one region to read from, which starts from the read index.
        memcpy(dest, m_buffer + m_readIndex, length);
    }

    // Increment the read index and wrap around at the end.
    m_readIndex = (m_readIndex + length) % m_sizeBytes;

    // Update the read and write sizes.
    m_writeBytesAvailable += length;
    m_readBytesAvailable -= length;

    return length;
}
</pre>
<p>And that&#8217;s it! There is a full implementation available <a href="https://github.com/samizzo/ring-buffer" title="here">here</a>. Note that it makes no attempt to be thread safe! You should lock as appropriate if you use this in a multi-threaded environment.</p>
<p>Next time we&#8217;ll look at using this class to dynamically generate a continuous audio stream!</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/ring-buffers-circular-buffers/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The case of the continually checked out prefabs</title>
		<link>https://www.horsedrawngames.com/the-case-of-the-continually-checked-out-prefabs/</link>
		<comments>https://www.horsedrawngames.com/the-case-of-the-continually-checked-out-prefabs/#comments</comments>
		<pubDate>Wed, 17 Jun 2015 07:49:33 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[unity]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=109</guid>
		<description><![CDATA[I&#8217;ve been helping out my friends over at Three Phase Interactive on their game Defect: Spaceship Destruction Kit a little bit. The game is being developed in Unity, and they&#8217;re using Perforce for source control. We&#8217;re using different combinations of the built-in Unity Perforce support and the P4Connect plugin. We&#8217;ve had a strange issue in Unity for...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/the-case-of-the-continually-checked-out-prefabs/" title="ReadThe case of the continually checked out prefabs">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve been helping out my friends over at <a href="http://threephaseinteractive.com/">Three Phase Interactive</a> on their game <a href="http://sdkgame.com/">Defect: Spaceship Destruction Kit</a> a little bit. The game is being developed in Unity, and they&#8217;re using Perforce for source control. We&#8217;re using different combinations of the built-in Unity Perforce support and the <a href="https://www.assetstore.unity3d.com/en/#!/content/25523">P4Connect</a> plugin. We&#8217;ve had a strange issue in Unity for a while now where it would try to check out two specific prefabs seemingly randomly. There seemed to be no reason why, as the prefabs weren&#8217;t directly being changed!</p>
<p>After much searching around and digging, I was able to discover the reason for this. If you have a prefab in your project with a <code>MonoBehaviour</code> which implements the <code>OnValidate</code> function, Unity will at times execute the <code>OnValidate</code> on prefabs that aren&#8217;t in the current scene and are not even selected in the project tab.</p>
<p>In the <code>OnValidate</code>, if you assign any values to certain members, Unity then flags the prefab as dirty, and thus when you save the project it decides that it needs to be checked out of source control. In our case the values weren&#8217;t actually changing; they were being set to the same as their initial values, so the prefabs would be checked out but then there wouldn&#8217;t be any changes in the file.</p>
<p>The most common times when Unity runs <code>OnValidate</code> appear to be when entering play mode, and when Unity rebuilds after code has changed.</p>
<p>I was able to reproduce this behaviour in a small test project, but only when modifying properties of the <code>GameObject</code>&#8216;s transform (e.g. setting <code>transform.rotation</code> to identity). Setting serialised class members didn&#8217;t seem to trigger this issue, so it seems that it only happens if you set built-in Unity properties (maybe it hooks into the property setter).</p>
<p>In SDK the way I solved this was to add this code to the top of the <code>OnValidate</code> methods:</p>
<pre class="brush: csharp; title: ; notranslate">
#if UNITY_EDITOR
   if (gameObject.hideFlags == HideFlags.HideInHierarchy)
      return;
#endif
</pre>
<p>However in my test project, that didn&#8217;t work, and I had to instead do this:</p>
<pre class="brush: csharp; title: ; notranslate">
if (transform.rotation != Quaternion.identity)
   transform.rotation = Quaternion.identity;
</pre>
<p>I suspect that only changing the values if they are different is the more reliable method; in SDK prefabs seemed to be set to <code>HideInHierarchy</code> but that wasn&#8217;t the case in my test project. I&#8217;m not sure why as I couldn&#8217;t see anywhere where it was changing the hide flags, so I may have to go back and change it in SDK.</p>
<p>It took a while to figure this out, but it was thanks to a post over on the NGUI forums <a href="http://www.tasharen.com/forum/index.php?topic=6766.5;wap2">here</a> and a post on Unity answers <a href="http://answers.unity3d.com/questions/623461/prefabs-in-git.html">here</a> that I was able to track this down!</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/the-case-of-the-continually-checked-out-prefabs/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Shader syntax highlighting in Visual Studio 2013</title>
		<link>https://www.horsedrawngames.com/shader-syntax-highlighting-in-visual-studio-2013/</link>
		<comments>https://www.horsedrawngames.com/shader-syntax-highlighting-in-visual-studio-2013/#comments</comments>
		<pubDate>Mon, 15 Jun 2015 04:10:17 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[cg]]></category>
		<category><![CDATA[glsl]]></category>
		<category><![CDATA[hlsl]]></category>
		<category><![CDATA[shaders]]></category>
		<category><![CDATA[visual studio 2013]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=95</guid>
		<description><![CDATA[If you edit shader code in Visual Studio 2013, you might like to use NShader to get syntax highlighting. NShader was originally written by Alexandre Mutel. His version is available here but it only supports VS2008, VS2010, and VS2012. Issam Khalil had forked it and added VS2013 support, as well as Unity shader highlighting. I&#8217;ve...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/shader-syntax-highlighting-in-visual-studio-2013/" title="ReadShader syntax highlighting in Visual Studio 2013">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>If you edit shader code in Visual Studio 2013, you might like to use NShader to get syntax highlighting. NShader was originally written by Alexandre Mutel. His version is <a href="https://nshader.codeplex.com/">available here</a> but it only supports VS2008, VS2010, and VS2012. Issam Khalil had <a href="https://nshader.codeplex.com/SourceControl/network/forks/IssamK/VS2013andUnityShaders">forked</a> it and added VS2013 support, as well as Unity shader highlighting.</p>
<p>I&#8217;ve <a href="https://github.com/samizzo/nshader">forked</a> Issam&#8217;s code and added a couple of features. The installer for the extension can be downloaded <a href="https://github.com/samizzo/nshader/releases/download/2.0/NShader.vsix">here</a>. This installer can be used to install into both Visual Studio 2013 and 2015.</p>
<p>You can now override the file type detection by specifying, on the first line of a shader file, a comment like so:</p>
<p><code>// shadertype=&lt;type&gt;</code></p>
<p>where <code>&lt;type&gt;</code> is one of:</p>
<blockquote><p>hlsl<br />
glsl<br />
cg<br />
unity
</p></blockquote>
<p>This will force the file to use the specified syntax highlighter. This is case sensitive and must appear exactly as above. Otherwise if the <code>shadertype</code> tag is not present, the file extension will be used to decide what type of highlighting to use. The following extensions are recognised:</p>
<blockquote><p>
HLSL syntax highlighter &#8211; .fx, .fxh, .hlsl, .vsh, .psh, .fsh<br />
GLSL syntax highlighter &#8211; .glsl, .frag, .vert, .fp, .vp, .geom, .xsh<br />
CG syntax highlighter &#8211; .cg, .cgfx<br />
Unity syntax highlighter &#8211; .shader, .cginc, .compute
</p></blockquote>
<p>The keyword mapping files that can be placed in <code>%APPDATA%\NShader</code> now override the built-in mappings. For example, if <code>float</code> is mapped as a <code>keyword</code> in the built-in mapping for GLSL, it can be changed to a <code>type</code> by adding the following line to <code>%APPDATA%\NShader\GLSLKeywords.map</code>:</p>
<blockquote><p>TYPE=float</p></blockquote>
<p>Multiple words can be specified on a single line by separating them with spaces or tabs. The zip file contains the built-in keyword mapping files as examples.</p>
<p>I&#8217;ve also added a separate colour setting for anything that is defined as a <code>type</code>. This should appear in Tools &gt; Options &gt; Environment &gt; Fonts and Colors in the display items list for the text editor colours. Scroll down to &#8216;n&#8217; and you should see all the NShader colour settings. The new setting is &#8216;NShader &#8211; Type&#8217;.</p>
<p>If you are having troubles with files not highlighting, try uninstalling NShader first via Tools &gt; Extensions and Updates. Also make sure you restart Visual Studio after installing NShader!</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/shader-syntax-highlighting-in-visual-studio-2013/feed/</wfw:commentRss>
		<slash:comments>52</slash:comments>
		</item>
		<item>
		<title>BinaryFormatter on iOS</title>
		<link>https://www.horsedrawngames.com/binaryformatter-on-ios/</link>
		<comments>https://www.horsedrawngames.com/binaryformatter-on-ios/#comments</comments>
		<pubDate>Tue, 06 May 2014 15:28:12 +0000</pubDate>
		<dc:creator><![CDATA[Sam]]></dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[serialization]]></category>
		<category><![CDATA[unity]]></category>

		<guid isPermaLink="false">http://www.horsedrawngames.com/?p=88</guid>
		<description><![CDATA[If you&#8217;re trying to use a BinaryFormatter under iOS you may discover that it doesn&#8217;t work. You may get exceptions like &#8220;ExecutionEngineException: Attempting to JIT compile method ..&#8221;. This is because by default the mono BinaryFormatter uses runtime generated class serializers. This won&#8217;t work on iOS because JIT compilation is not permitted. To get around...  <a class="excerpt-read-more" href="https://www.horsedrawngames.com/binaryformatter-on-ios/" title="ReadBinaryFormatter on iOS">Read more &#187;</a>]]></description>
				<content:encoded><![CDATA[<p>If you&#8217;re trying to use a BinaryFormatter under iOS you may discover that it doesn&#8217;t work. You may get exceptions like &#8220;ExecutionEngineException: Attempting to JIT compile method ..&#8221;. This is because by default the mono BinaryFormatter uses runtime generated class serializers. This won&#8217;t work on iOS because JIT compilation is not permitted. To get around this, you can force mono to use reflection to perform the serialization instead. You can do this by inserting this line:</p>
<pre class="brush: csharp; title: ; notranslate">
Environment.SetEnvironmentVariable(&quot;MONO_REFLECTION_SERIALIZER&quot;, &quot;yes&quot;);
</pre>
<p>somewhere in your project (e.g. in the Awake() method of the MonoBehaviour that needs to use serialization).</p>
<p>You could also instead use <a href="https://code.google.com/p/protobuf-net/">protobuf-net</a>, which is a serializer for .NET that uses Google&#8217;s <a href="https://code.google.com/p/protobuf/">Protocol Buffers</a>.</p>
]]></content:encoded>
			<wfw:commentRss>https://www.horsedrawngames.com/binaryformatter-on-ios/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
