Moving projects to Unity 5

After Unity 5 released I decided to upgrade a few of my older projects and see what happened. So I opened up SourceTree and made sure there was a commit to safely rollback to if everything exploded.


Just Shmup Dammit. Unity removed the shortcut properties .rigidbody .audio etc. as they were performance traps. They look like direct variable access, they are not. I’ve already talked about this in a previous performance post. This and 1 instance of a tag compare were the only things that changed in the automatic upgrade process. The tag compare was a compile error, all that needed to be done was remove quotes around a variable name.

Everything then ran as before.


Unity updated the scripts, highlighting a few places where I had been lazy and had multiple .rigidbody in the same block. Other than that all test scenes ran as before.

Project Red-Room

Well and truly still in it’s early stages, first person exploration game. Obviously required first person controller of some sort and makes heavy use of Pro Core’s ProBuilder. This asset required a new version to function correctly in Unity5. This required a fair bit of back n forth, lots of discard local changes, only due to a bug in the version I was using at the time, which I assume has been fixed since, it was only converting ProBuilder prefabs if they were in the currently active scene when I imported the newer version of the asset. This might be down to how Unity5 changed prefab storage in scenes.

I had been piggybacking off of Unity’s first person controller and using many of Unity’s Image effects. All of these have changed. At the very least in 5 they are all C# now. That’s great but it meant redoing some settings to update to them. The newer first person controller makes more sense, to me at least. It’s 1 script not 3 interacting js behaviours. However it has lost some functionality, handling moving platforms and easy ways to toggle off features. So these had to be added back into the newer version.

PhysX 2 to 3 changed a bit. My door prefab’s were extremely broken. They were having the physics freakout we all love with ragdolls. Hinge’s needed new settings, so the door wasn’t trying to be pulled inside the doorframe/wall next to it. The other change that got me was the door frame itself, previously a solid single object was no longer allowed due to the way I had set it up, it was not a convex shape. So altering the door prefab to use 2 boxes and 2 capsules instead of the door frame mesh itself solved this issue.

Certain shaders seem to now be much slower than previously. A grid of 100+ characters was causing frames to drop to the teens. I’m fairly certain it was not previously. Fortunately in this case there was no reason for them to be using a special shader so changing their material to use the new Unity 5 standard shader has solved this problem. This put the fps in the same area back up to well above 60.

Fog has changed. It and many other settings now live in the Lighting window and also requires that the global fog image effect is added to the camera.

Unity and getting The Player

So I saw something very much like

A few things first. If its performant then it’s ok, sure. I don’t have the Unity source code so I can only infer things from what they have talked about.

Lets psuedo what this is probably trying to do


Now lets create the psuedo for what is actually happening

That’s pretty expensive and not what we actually wanted.

Lets talk the quick n dirty way to make this a bit more like what the original pseudo intended. The original code indicates that there is only 1 player and we want access to it somewhere else. Sounds a lot like the exact conditions for a singleton. For a MonoBehaviour we can do this in a number of ways. We’ll discuss more robust solutions another time. So the least robust but quickest is.

In the Player.cs


and then the orig code becomes




If somebool is a property and not a field or has knock on effects, we perhaps even go further and look at using the OnBecameVisible, OnBecameInvisible messages.

Shader updates and inspectors

It’s been a busy few weeks. I’ve been knocked out a bit with a cold/flu thing and PAX. So there’s not as much to report as I would like but here’s the highlights.

PAX was great. Being in the bigger venue meant we could actually get to panels without waiting multiple hours in the cold and rain. Got to see lots of panels with indie devs and talk to them on the show floor. Numerous people told me GCAP is probably what I actually wanted to go to and their not wrong. It just wasn’t going to work out this year. Next year hopefully.


updated substances and all the maps shader

I’ve updated the shader in a bunch of ways. It’s more optimised, previously it was just using a separate texture for each map, now its all packed in channels. Considerably less total gpu ram usage and runs faster, few things that were previously floatx and how just single floats and things that used to be separate samples are now just swizzles. This simple sample scene is running comfortable at hunders of frames even on my mac air.

ao sample grey scale

Grey AO

ao sample colour

Coloured AO

I was talking to Tony at work about what I’d been messing with and he mentioned that it really bugged him that AO was always grey scale. So I have a first draft coloured AO in the shader and a node to generate it from diffuse, ao and height in Substance Designer. The early results are interesting, its kind of a very local faked GI or PRT. In any event I like the way it looks, it makes everything appear much richer instead of washed out.

custom material inspector

Next up was a custom material inspector for the shader, just so it can hide properties that aren’t being used, eg. here lightramp textures are not shown as they are not turned on, same with occlusion strength. Also I wanted to have both sliders and numbers showing for float ranges.

Also created a simple light ramp and gradient ramp texture creator (the yellow and blue ball above is using a dual colour ramp shader) so I didn’t have to keep going back n forth to photoshop etc. to create ramps. This is done by creating a custom editor window.

texture ramp creator



I wanted to be able to chain together and merge different patterns and randoms etc. to generate dynamic anim curve style data. Specifically so I could not have to create custom animations for things like moving/flickering lights in the scene I’m working on. My first attempt worked great and code made sense and was a small and easy to maintain and extend. Unfortunately the way I was using inher didn’t play nice with unity inspector. So I redeveloped it as flat (and right now just a single class). The code is not as nice (it’s not soul code anymore) but it is entirely configurable from within the unity inspector.

custom generator inspector

This required both a custom inspector for GenerateDriver class and PropertyDrawer for Generator class. I’m particularly fond if the real time preview. This head bob a few of these moving different local pos axis and lerping between idle and moving bob based on velocity, ~10 lines.



Finally here is some very early stuff I’ve been working on for the Red Room. Mostly just upping my proficiency with Substance Designer.




Parallax Offset

So sometime last week, while playing Substance Designer for a I’m working on, I put some height maps into Unity’s Parallax Bump Spec shader. This sent me down an interesting rabbit hole. First off Unity’s parallax is an interesting hack/shortcut.


No parallax


Unity’s parallax

unity para

That’s it. Very cheap and for low heights the effect is still impressive. But at large heights and longer objects the textures begin to slide, thing start to look like they’re made out of chrome and their texture is actually the environment map. Why? Well its not how Parallax offset mapping/parallax occlusion mapping/Steep parallax offset mapping/relief mapping etc. work. They all rely on some form of ray marching through texels of a height field/map. Basically we have some starting point, the uv being render, we then move in the view direction across the surface of the texture incrementally. The distance per step is determined by viewing angle. Each step it samples height, if the height is less, we’ve intersected the height field surface. When it can be afforded a binary search is then performed between the previous and current sample to find a more accurate height for this frag, it greatly reduces height banding. This gives us a new ‘depth’ of the frag and a uv offset to sample all other maps with. here and here give good overviews

Parallax Offset


Well occlusion had to come next didn’t it. Its expensive. It uses the same principle. Once you find the offset, you then use the same ray marching ideas to move towards the surface of the height field in the direction of the light dir. If you make it to the surface without dipping below the height then not occluded, if you do hit something the light doesn’t reach you.

Smoothing these out was needed, I wanted to find a cheap way to remove the misses and the aliasing. My current method is to use lower mips. One of the recommendations for height map aliasing is smoother maps in the first place, which I have also played with a bit in my demo scene. Mips will smooth for me automatically (they’re already there I just needed to use them) and will still allow for extreme close ups to have that detail. Unfortunately it was not as easy as tex2dlod, unity surface shaders don’t support it it seems. But they do support tex2dGrad. This worked, much of the aliasing and sparkling was gone the very sharp edge remained. To smooth it (or rather make it less regular), compare the sample to that of an even lower lod and fade based on difference between the two.

Parallax Occlusion

para occ

The solution is not overly accurate but it is smooth, consistent and predictable. There is little to no, sliding, popping or sparkling. Also it only works in dx11 mode in Unity. I wanted to see if it was possible using only Unity’s surface shaders instead of writing glsl or cg from scratch, it is but it means changing renderer causes it to fail, due to using tex2dgrad inside control flow statements: X6077. This strikes me as odd as I’m fairly sure what I’m doing is legal, esp since unity graphics emulation thinks it’ll work on openGL ES 2.0. It might be pure related to Unity’s conversion from surface shader to cg is renderer dependant and is stumbling somewhere.

Some of the problems with this method;
Everything is pushed in (away from surface norm), so things shrink.
For great heights texels on slopes get pulled in ways they were never intended to, could try to remedy this with tangent space tri-planar mapping, at least add some noise over the stretch.
Its expensive, some quick numbers out of the Unity viewport, para occ is ~450fps, para without occ is ~650fps, Unity’s offset is 2000-400fps. That’s on a gtx670 in a window that is about 1600×900.

After much fiddling with tuning paras, like min and max steps, I was happy… for a time. I wanted to see what else I could push with the other map types out of Substance. Ambient Occlusion was the next map of interest. I’ve previously used AO in substance as an information source for the diffuse map. I tried mixing AO with both depth and nDotL (normal . light). The results again and not accurate at all but the effect was surprisingly good, to me at least. It gave fake soft shadows across the surface.

Directional Ambient Occlusion

amb dir only

Final result.


This is by no means the best, most complete or most performant way to accomplish these tasks. Displacement mapping would most likely be much faster and produce smoother results.


Different angle

Normal map only

none skew


Unity Parallax

unity skew


Parallax Occlusion with Directional Ambient

para all skew


Proportional Navigation

Another in the line of mesmerizing demos. Check it out here. At some point soon this will replace the current naive tracking the missiles do in Just Shmup Dammit and eventually become part of JGDLib. I was prompted to look into it after some of the students chose to look into missiles swarms ala Itano circus. They mostly ended up with variations of flocking algorithms. This is not that, it’s what’s actually used in many real missiles and apparently a few of the more simulation based games. 

Readying Something For The Assetstore – Part 4

So remember when I said I was going to feature freeze JGDLib, well I lied. After watching the Unite keynote, I decided I needed to celebrate the incoming PBS pipeline with a collection of entirely unrealistic, definitely not physically based shaders.

Check it out here

These now require a little bit of documentation, then it will be feature freeze and commence scrounging for some testers.

Reading Something For The Assetstore – Part 3

Documentation is complete and I’m feature freezing JGDLib at this point so I actually push ahead with its release. Without doing this, I fear I’ll fall into the programmer trap of continually finding new awesome things to add to the library but never release it. No one benefits from that.

So what happens now? Quite a lot actually. I registered my company name and want to put this under than, so its website needs to be up and running (a topic for another blog). I need to do some closed testing with users. This will most likely be work colleges. The focus will be; usability of the software itself, finding both weaknesses documentation and bug hunting. My main concern right now is that I know how to use these because I wrote them, but I need to be so obvious, self-explaining and well documented that I’m not flooded with support emails from people who have paid for lib post release.

On a side note, the last thing I added to the lib was a projectile solver. It solves the launch angle for a constant speed projectile to hit a moving target. It handles either, both or neither falling under gravity. It’s kinda mesmerizing.

Fixing Mono Auto-Formatting

So at work Unity and Mono seem quite unhappy with the lack of admin rights. The most annoying consequences of that is Mono defaulting to a crazy auto formatting. With a project open in mono we can fix this by changing two settings.

Go Project->Solution Options. In Code Formatting change c# source code to Microsoft Visual Studio.

Then the same settings in Mono. Tools->Options. Again in the source code section, Code Formatting, c# to Microsoft Visual Studio.

While you’re there I also normally use behaviour

Readying something for the AssetStore – Part 2

So I think I’ve decided to charge something for what I am now calling JDGLib, Just Games Dammit being the business game I registered.  I came to this conclusion for a number of reasons;

  • It’ll be great to see any money come from this effort
  • I’ll feel obligated to respond to support emails/requests so at least if it costs money I’ll feel like that support is already paid for
  • Paid asset will almost certainly lower the number of users, which makes me less anxious

Also good doco will have to be my savior here. So this is what I’ve completed so far. I’ll also need to do up rational, class explanations and usage for Object Pools, Easing and Camera Shake. I’ll link to these in the asset store listing so I’m envisioning that the clear use cases and usage methods will stop people from buying it thinking its something it isn’t.

Unity Optimisation Basics Part 3


Which of the following should execute faster?

If you guessed any of them, you are wrong. That’s right, calling them 10000 times a second there is no single method that consistently executes faster than the others. (Not entirely true but I’m making a point here.)

So the compiler optimised out the literal string for us, that’s good to know. Lets look at the profile results.


J’accuse. Everything is allocing but CompareTag, the method in gameobject that is recommended by Unity as the method to, you guessed it, compare tags. Where at all possible use CompareTag. the GC is your enemy. It’s an interesting situation. The alloc comes from get_tag(), which is triggered by the .tag property, which could be a call to unity native code that results in a mono string being created or just due to the immutable nature of strings in mono. I know I’m guilty of it too but if you can find a .tag anywhere in your code base do your darnedest to get rid of it.


Speaking of strings. String concat or string.Format or StringBuilder for simple wave counter in JSD.

Format looks nicer, kinda, probably a lot if you like printf.


Well crap, Format is out, it’s the slowest and the most trashy. StringBuilder vs regular concatenation is a bit trickier. For my purposes I can avoid calling the function for all but when the current wave actually changes, so less than once a second, keeping the alloc as low as possible suits me.


Unity Optimisation Basics Part 2

Math is hard

Currently in JSD, the Seeking missiles are taking up WAY more cpu per frame than I would have anticipated. As much as 30% of the total cpu load per frame when there’s about 40-60 of them active. This is pretty much all its doing.

Part of the problem is gameobject compares aren’t trival, see. The  translate and smooth rotate, are expensive. For almost all of the other objects in the game these happen during enable and never again. If I made the missile a ‘plasma ball’ then I could simplify the maths a bit here by not needing to update the orientation of the object .


I was doing a little bit of hunting around to find more on the cost of GameObject.Activate, which gets hit in the profiler for SetActive(true). I found this. Needless to say I had to test this theory that enable might be better than active. So Lets dig in.

This section is 3 methods running simultaneously so you can visualise the ratio of performance they require.

First up Instantiate and Destroy 100 simple boxes with RigidBody every frame.

all_instHiLi all_destHiLiI’ve highlighted the Destroy here too. Its separate as Destroy seems to add the item to a list Unity keeps internally and handles next frame (as I understand it.). Most of the memory here seems to be in native land not in GC land but we are still generating some garbage. Its also responsible for a big chunk of the ‘Other’ time, which I can only assume is Unity native code creating the GO, components and serialise, deserialising from the prefab.

Next, Deactivate 100 in a list, activate the next 100 in the list. This occilates each frame. This is the basics of an Object Pool.

all_activateHiLiNot a crazy amount faster but it is faster and there is no Destroy and no GC to speak of.

Ok lets try this enable disable trick.



Lets see them in isolation.

Instantiate and Destroy – 9.3ms to 10.3ms

solo_instNoGCInst without the GC showing

solo_instGCInst WITH the GC showing, ouch.


Activate/Deactivate – 6.7ms to 8.9ms

solo_actNot as good as we’d like but definitely better and no GC.


Enable/Disable on collider and renderer – 2.5ms to 3.0ms

solo_endisMinamalLittle bit of GC but this is insanely good, what’s going on.

Enable/Disable Generlised – 8.3ms – 15ms
Here I add the 2d variants, audio and animator components to the mix to create a more general solution, not the object being made just to the enable disable code, as activate/deactivate and instantiate/destroy would handle any combo and any number of components. In real world it would need any scripts you’ve added to the component to be disabled too, most likely.


GC is going crazy due to all of the GetComponent, remember that .rigidbody or .audio etc. are properties that basically end up calling GetComponent.

Ok, so once we try to extend the enable/disable trick to a more general solution it becomes worse than just instantiating and destroying. It is a good trick to remember though, if you had a very simple object it is a far more surgical method.

For the sake of science I tested this same set up for all modes with 10 and 500 cubes. Physics engine didn’t much care for 500 each, it actially made GameObject.Activate way more expensive than anything else. But the test was running at fractions of an fps due to way too many overlapping cubes.

With 10, it tells a different story.


Yes the order of best is the same, Inst about .8ms, Act about 0.7ms, Enab about 0.4ms. But those spikes, those spikes are where the Enable/Disable takes 7ms, yes SEVEN up from 0.4. It’s entirely down to it triggering a GC collect.

What if it only ever asks for things that do exist? I tried it with a few empty component scripts I create, no more GC. Remove them from the prefab, GC comes back. So if it only ever looks for components that do exist then its faster with no down sides. Its worth investigating a custom per prefab pool that uses this knowledge.

Well now I have to test what a find all Behaviours will do… Well that kinda sucks. Collider and Renderer are not behaviours, so you need to special case them. Something like

But that totally works and is nicer to look at, kinda. It runs at 0.3ms average but those spikes don’t go away, due to us now using GetComponents alloc’ing an array.

So not set active?

Well no, its a general solution that handles all cases, is mostly unintrusive to your codebase and can easily be written to never incur any GC Alloc. More over, its worst case is far more predictable and acceptable than the others in their general usage. Given that the GC is mostly out of our control and Unity doesn’t provide a no alloc way of fetching components the we cannot control the perf spikes due to the garbage being created. So unless you have a very specific set of components that you know exist and can access directly or already have around, you probably don’t want to enable/disable. All that being said, I’ve added ‘Intrustive enable disable pool object’ to my todo list.

Don’t do things you don’t need to

This isn’t at all Unity specific, its just general programming. What’s the best way of optimising ‘this’ code? Not doing it at all. For example, in some of my testing I wrote this;

Works and looks fine. But it’s (potentially) doing twice as many GetComponents as it needs to. Changing it to this

gave a non-trival performance improvement. Doesn’t lower GC Alloc as this seems to only come from requesting a Component that does not exist. It’s the same reason Unity recommends that you grab local references to any and all components to you need to access in your scripts during Start or OnEnable instead of during Update, FixedUpdate, etc.

Readying something for the AssetStore – Part 1

So I decided that since I often want the same collection of features in all my Unity projects/protos I should bundle all of that together into a lib and make it available on the asset store. These things being Splines, Easing, Pools, Live csv data and a few others are all things that I’ve written partially because I wanted to or because things on the assetstore didn’t quite have the features I wanted.  Bits and pieces of it I’ve already given to students on several occasions and the process is quite odd.

On one hand I think these are very useful and in some cases more feature rich than their competitors on the AssetStore right now, so I could charge money for this lib. At the same time, they make sense to me, not necessarily to everyone in the world and especially not to the non-programming users of Unity, of which there are many. I don’t feel I have the time to answer lots of support requests. So do I charge lots for it so not many people pick it up on a whim or nothing(or not much) so people don’t expect a high level of support. To further complicate this I’d love to be able to just tell the students to go get my lib from the asset store but if its expensive then I cannot really do this, they don’t have money and its a conflict of interest.

While I’m on the topic; code libs are easy to demo in the AssetStore package set up. They don’t have cool screenshots. The best solution I’ve seen others come up with is to create basic feature tutorials as screen shots or captures of the editor with arrows and text everywhere explaining what you’ve added and how easy it is to use to do x,y,z now.

I plan to discuss these little systems in detail and my journey of getting them onto the store in future posts.

Unity Optimisation Basics Part 1

I recently decided to run the unity profiler over JSD and see what could be improved, this is just a quick review of my findings.

Searching is bad.

I already avoid all Find and GetComponents when ever I can so there weren’t many of them to find. I don’t recall if it was AltDevBlog or the Unity Blog itself or in a Unite or Learn video but it doesn’t matter. GameObject.Find*, Object.Find* and GetComponent are all expensive and wherever it was, explained that its simply because unity does a linear search through the collection to find them. Makes sense in a way, even if they were O(log n) it would still be expensive to do them all the time and would require the internal storage to be not cache sensitive or lazy.

Collision layers, use them.

JSD has a lot of trigger rigidbodies, I had set it up so bullets didn’t overlap with withselves and never gave it another thought, until I saw 126 calls to OnTriggerEnter in 1 frame. Lots of bullets overlapping enemies however. It did a few checks and threw it away. Changing bullets to be in either a only collides with player layer and vice versa (an only collides with enemies layer) reduced this down to much more acceptable levels. This also drastically reduced the number of contact pairs the phys engine has to create and maintain which greatly lowered the overall and consistly high amount of cpu time spent in the physics engine.

yield rarely

The bullet spawners had a yield still in them from an earlier debugging attempt to prevent infinite loops during testing, this seemingly harmless line

was causing an additional 10% overhead on that function call. This again is not surprising, if you haven’t have a look at its not an inconsiderable amount of work to make that co-routine happen, even if the line with the yield never gets hit.

Pools are not a silver bullet

I use object pools (of my own creation) to avoid trashing memory which is mandatory on mobile if not everywhere. You should avoid allocs during gameplay like the plague. I found however that activating objects (.activeInHierarchy = true) is still quite expensive.

Surprisingly, splines are not using much at all, neither is overall rendering.

Unity in a Repo

I’ve thrown together a quick little google doc of how I use source control and unity together. This isn’t complex but I found in a quick google that a simple guide was hard to locate.

It deals much more with how I use unity in a repo it is not meant to be a guide of how you MUST use it just a way that works for me. It is not really a discussion or explanation of how source control works there are plenty of other places to understand that.

View it here

Just Asteroid Dammit Core

Didn’t get to spend as much time on this as I would have liked. But we do have a ship and asteroids and sub asteroids spawning and floating around with the 2d physics system.

I made them all super bouncy by adding a PhysicsMaterial2D as the default material was a little flat. The trick for my wall wrap is boxes on the edges of the screen using a OnTriggerExit2D, which flips their position based on a scale and if their velocity matches a dot product. The dot product ensures that they are trying to leave the screen not enter it from that side, without it objects would flicker back and forth between sides.

Try it here

Just Invaders Dammit Core

Next up was space invaders.

Try it here

With this one the its a few little tricks that are to be learned from. Don’t want the player to go off the screen? Well there’s heaps of whats to get that to work but for a core gameplay prototype, just put a clamp in there and dial it in. In this case player’s transform x is not allowed to go beyond -2.9-2.9.

Want a grid of enemies, well generate them. The enemy manager takes a starting point transform and how many rows and cols you want and how far apart they should be. In this case that seemed easier than copy pasting GOs. It also lines up nicely as we then child all those enemies to the enemy manager and it controls their movement and uses their colliders to determine when to change direction. It also chooses which enemy should fire.

I’m using triggers on constrained rigidbodies on almost everything here.

Just Flap Dammit Core

I posed my new Scripting for Game Development students with creating a core prototype of Flappy Bird. Doesn’t take too long to get the core running and its well under 100 lines of code.

You can try mine here

For me, the trick at this point to getting it to feel even remotely good is totally bullshit physics values. Right now the bird is .5m, gravity is -16m/s/s, mass is 1kg with a drag of .4 and a impulse strength of ~10n.

Update: With the addition of about 15 more lines we now have personal bests to beat.

Try out version 0.2 here

Shaky Cam WIP 2

Threw together a quick demo to show the variance possible in the shaky cam setup I described earlier. It sends the shame shake vectors to all cameras, the different results are due to different spring constants and different rigidbody linear dampening values.

Try it here

Totally not peggle – Part 3

Playable here

Didn’t get to spend as much time on it tonight as the last two but managed to get camera shake and beginnings of some basic emotion. Some pegs spawn with eyes, right now all they do is ‘panic’ (pupil shrinks) and look at a ball if one is close. Otherwise they just blink randomly and look around. Looks cool though.

Shaky cam

Build here

Quick job of putting together a 3 dim of freedom spring with linear limits. I tried using the built in springs but they were a little crazy. At the moment it still relies on the rb to maintain velocity and dampening, I’m not sure I like that so I’ll probably move that out so it simulates itself in isolation of whatever the physics engine may want to do.

Totally not peggle – Part 2

Playable here

Completed this after work, apart from a short break here and there ( for dinner and such). Lots of basic juice as been added. Music is from Incompetech. Sound effects created in Bfxr. Easing is done using a little Easing utility I wrote a while back. I’m pretty happy with it for what is all up only about a day worth of work.

The big things I haven’t gotten to yet are; cracks in the pegs, proper menu and world map, camera shake and touch friendly input. Perhaps tomorrow.

Totally not peggle – Part 1

Playable here

Something I threw together after work today. Made with Unity using 4.3’s new 2d sprites and NGUI. Box2d (which is what the new 2d physics system in unity is) is SOOO much better at this kind of interaction than physX was.

Think I’ll add more to it later tonight and tomorrow after work.


UPDATE: Didn’t end up doing anymore last night. Ok so HERE is the same thing but with a auto generated grid level. Now to juice it.