Categories
programming Unity3D Unity3D-tips

London Unity #luug talk 2015 – Customizing Unity Editor

Slides from my talk earlier this evening:

LUUG-2015-Editor Customization-v1.3

And if you were there, and haven’t read @lucasmeijer’s blog post yet: http://blogs.unity3d.com/2014/06/24/serialization-in-unity/

Categories
programming Unity3D

#Unity3D plugin review: Advanced Inspector

The author of Advanced Inspector gave me a free copy over Christmas. I’d considered it many times, and always ended up choosing not to buy, and write my own fixes/workarounds instead. So I was keen to try this out on a hobby project and see how well it works in practice.

What is it?

A replacement for Unity’s built-in Inspector. This (optionally) changes the editing interface for every single Component in your Unity projects.

Why do we need it?

When you run Unity, you get the standard multi-pane IDE that is the Unity Editor. Whether you’re a programmer, a designer, or an artist, this is your main portal into Unity, and the starting point for all your work.

Anything you select in the 3D/2D scene causes an Inspector panel to appear, with all the editable data about that thing. Unity’s built-in Inspector is very basic; by modern standards of GUI/UX, it sucks. Fixing GUI is very expensive, so instead … Unity has gradually been making the Inspectors more and more customisable.

Traditionally this was very hard to do; in the last 12 months it has become much easier, and Unity has unlocked more features. To date, I’ve not been sure if the 3rd party plugins are fully using the new features.

Categories
Unity3D-tips

Easy parametric animations in #Unity3d with code and curves

iOS forces you to use pretty animations: if you don’t tell it otherwise, it will use “ease-in/ease-out” curves to make things feel … smoother, less jerky.

Unity is made for programmers; changes you make to position, size, rotation, etc all happen instantaneously. By default, they won’t even animate, will teleport instead.

So … moving from “prototype with no animation” to “prototype that won’t hurt people’s eyes, and I can share”, what are some tips and gotchas?

Categories
art

A Whiteboard Xmas Card for everyone

What can you draw with a whiteboard, if you’re not an artist? Let’s see..

Many of my friends live on different continents. It was too late to post cards, and I was staring blindly at my whiteboard when I had an idea: A picture for everyone, photographed, emailed … Then wiped clean. A transitory, ephemeral, virtual gift made out of something physical and real.

(there’s a background to this, see below the images)

PS: apologies for variable quality – I was doing these as fast as possible, trying to get them out same day (Xmas Day).

IMG_20141225_224459 IMG_20141225_225137 IMG_20141225_230807 IMG_20141225_231300
IMG_20141225_232047 IMG_20141225_233613 IMG_20141225_234827 IMG_20141225_235750
IMG_20141226_000710 IMG_20141226_012840 IMG_20141226_013834 IMG_20141226_014528
IMG_20141226_020551 IMG_20141226_021514 IMG_20141226_022811 IMG_20141226_030250
IMG_20141226_031039 IMG_20141226_032140 IMG_20141226_033113 IMG_20141226_122938
IMG_20141226_123945 IMG_20141226_125359 IMG_20141226_133850 IMG_20141226_134557
IMG_20141226_135051 IMG_20141226_155430 IMG_20141226_160437 IMG_20141226_220730
IMG_20141226_222932 IMG_20141227_172428 IMG_20141227_174607 IMG_20141228_171110

If you didn’t get one, well … Maybe you should keep in touch more, my friend!

But seriously: I’m not finished yet. Watch your inbox.

Background

This Christmas, I did my first serious drawing/painting in 15 years, as a gift for someone. I was surprised (actually: stunned) how well it came out. Unfortunately, it wasn’t appreciated.

I wanted to make something positive out of it, anything. I’d poured too much time into that, and too much care, to write it off and move on.

Here’s the results. I took the theme of my original hand-made card: an image specific to the recipient, something that they (and their close friends) would recognize and understand immediately.

There’s a few that tie obviously to well-known people in Web, Education, Games industries.

Categories
dev-process entity systems Unity3D

Unity’s failure as an Entity System, example 1: Selecting things

Entity Systems in Unity… some examples of the problems

This is a new series of blog posts, where I’m going to document specific ways + concrete examples in which Unity fails (sometimes spectacularly) as an “ECS” game engine.

I like Unity; but the core architecture (which is very old) is a half-assed ECS, and if we’re to upgrade it into a really good, modern, architecture … we first need to understand exactly where it’s failing, and why.

So, let’s start with Selecting Things…

Background

Game

A 2-player card game where each player normally draws a card each turn, and then plays one or more cards. Sometimes (e.g. when discarding because “too many cards in hand”) they have to select more than one card at once.

Initial version of game will be 1-player versus computer. Very soon: want to upgrade to OPTIONAL 2-players on-screen, with one using the mouse, other using gamepad. Ultimately, want to also add over-the-internet multiplayer (which ends up interfacing with the codebase in a very similar way to the original 1-player-vs-computer, so we can ignore for now).

Code Situation

Player taps card. Now … we must inform many other scripts and independent systems, so they can choose to eg.

  • ignore (if invalid for current state of game)
  • react (e.g. zoom to display the card more clearly)
  • “select” internally (side-effects include: deselect other things)
  • advance the game (if it was waiting-for-input)
  • ..etc

Problem

What/where do you send the “player clicked on a card; can some piece(s) of code PLEASE deal with this??!!?” ?

Addendum

In Unity, only the low-level “card” object can sensibly detect it has been clicked on.

Both Unity’s Physics (old) and EventSystem (new) effectively force this via their core design. Both require you to attach scripts to the physical objects that will be clicked.

In practice, this is bad for OOP (and bad for ECS too). When there’s e.g. 100 cards all of which must be separately clickable, your code is really in the wrong place. You don’t want cards (which sometimes are in a deck, sometimes on the table, sometimes “virtual” (perhaps in a virtual, unopened booster pack etc)) … to be containing all the GAME logic required to know what to do when they’re touched!

Classic Entity System / ECS solution

  1. Create a SelectedByPlayer component
  2. Add it to the card
  3. Sit back, and relax. Code that cares about input will scan “get me all SelectedByPlayer components” on each frame, and react accordingly

Everything works automatically; any System/Processor that’s “waiting for a selection”, or “making render changes when selections add/remove”, etc … will pick up what it needs, with no work.

You can add new input-handling routines simply by adding them. That’s all. No other changes needed.

Attempting to solve this in Unity

UNITY 4.6/5.0

Maybe … NB: I’ve only just started using the new GUI/EventSystem in Unity 4.6+ .. create a custom Input event, and a custom InputModule that can understand that, and then put all the code for ALL affected systems/processors into one monolithic ugly, hard-to-maintain script from Hell.

I suspect that this code will be quite maintainable w.r.t. adding new Input hardware in future – e.g. allowing mouse vs gamepad. But it’s going to suck at the rest, all the business-logic and handling. Which is going to be > 95% of the maintenance cost.

You get one small benefit: you can separate-out different inputs (click versus drag). Sadly, in reality: 95% of game actions will be simple clicks. This is one of those “the code architecture sounded great in academic situation, but reality is so unbalanced, it works out less well in practice” situations.

This is a classic OOP solution, and has the downsides. The only significant benefit I can think of is that it’s a “known” Hell: if you’ve done a lot of OOP game coding, you’ll be familiar with the pain you’re going to run into.

UNITY CLASSIC

Make a new class “CardClickManager” whose sole purpose is to reference all the possible bits of OOP code that “might” need to react, and which has to be updated by hand EVERY TIME you modify, add, or remove some input-handling code ANYWHERE else in the codebase.

Pretty much the same as above, except it:

  • … is even more simplistic (no event-dispatch systems)
  • … making it even harder to maintain + debug
  • … is slightly more proprietary

Conclusions / Improving Unity

So far, I cannot think of any sane, maintainable solution here other than “suck it down and use OOP, and suffer forever”, or “throw away Unity GameObject/Component, and implement a proper ECS”.

That’s fine, though. That’s the point of these posts – to hilight situations where there’s no good middle-ground, where we must create the data-centric, cleanly-separated architecture of a modern ECS.

Counter-ideas very welcome! Comment away, guys…

Categories
computer games dev-process games design programming project management

How much should you use a Scripting language when writing a Game?

Ask 10 game developers if you should use more script code or less, and you will get 11 different answers. They are all correct: it’s very situation-specific. Use of scripting languages is highly dependent on the humans and the practical / project-management issues.

Why?

Categories
3DPrinting

Makerbot Replicator2 Upgrade: new fan duct

I reviewed a whole bunch of these on Thingiverse, and the best combination of simplicity and effectiveness appeared to be this one:

…but you want to print these at 0.1mm layer height, or less, and that’s difficult with the model above. So I tweaked it a bit:

NOTE: The WordPress authors can’t be bothered to implement safe/secure uploads; instead, they block ALL uploads (which is very stupid and doesn’t solve ANY security problems). This file has to be renamed when you download it. Stupid, stupid, stupid programmers.

WordPress Is CRAP.stl

Changes

The original model has two small circular screw-holes. Makerbot printers can’t print these very well – Both the official slicer, and the main commercial / open-source slicers get it wrong and print the holes in a bad way (untethered; it’s an obvious heuristic to fix, but no-one has implemented this yet). Net effect: the holes slide about during layer 2, and usually detach, and ruin the print.

To fix this, I cut a slice out of each hole, making them into hooks. This follows the design of Makerbot’s original fan duct, and makes the print easy to do even at high speed and low layer-height.

Categories
3DPrinting

3DPrinting tips: cooling, fans, and PLA temperatures

This is hugely important to 3D printing, and generally: no-one talks about it online (at least, not with any authority: more “blind leading the blind”). Which is silly: the engineering behind this is obvious (and it’s often obvious from looking at a 3D printer that it’s been under-engineered in this critical area).

NB: I don’t know which parts of “correct, obvious” cooling are blocked by stupid patents that should never have been granted. That might excuse the poor design of most printers today. Might.

My experience so far is that “more cooling of printed object is better”. But that’s an over-simplification…

Categories
computer games entity systems Unity3D

Towards a Unity3D ECS: what GUI? What features?

This year, one of my goals was to build a sane, powerful, viable Entity System / Entity-Component System within Unity3D. Something I could build current and future games on, and save a lot of dev-time (both in ease-of-use and in easily adding missing features that I wish Unity had).

So, progress?

Categories
server admin

Site disappeared? Apache ARGH!

Transferring server to new home.

Allowed it to install latest versions of core software.

Turns out … the lovely people at Apache have made major site-breaking changes to their config system, so that upgrading WILL break existing sites.

Took an hour to discover that :(.

Categories
Uncategorized

Epic saga of Unity3D deserialization of arbitrary Objects/Classes

(a summary writeup of the things I tried – based on this Unity blog post: blogs.unity3d.com/2014/06/24/serialization-in-unity/ – to get Unity 4.5 to correctly serialize/deserialize simple object graphs)

UPDATE: I belatedly discovered that EditorUtility.setDirty() is fundamental to Unity; if you have even one single call of this missing, Unity will corrupt data when you save the project. In some of the cases below, where everything was fine EXCEPT on fresh startup, I suspect that was the real problem: a missing setDirty(). I thought this method was cosmetic, but tragically: no.

This is not easy to read, it’s bullet points summarising approximately 2 weeks of testing and deciphering (plus a month or so spent learning-the-hard-way the things that are in the Unity blog post above. Note that the blog post only came out very recently! Until then, you had to discover this stuff by trial and error)

Serializable-thing:

– example on blog won’t work if e.g. your Class is an object graph.
– e.g. class Room { List doors; }. class Door { Door otherDoor; }
– …can’t be serialized. Can’t be stored as a struct, unless you have a GUID per “Door” instance. That’s no surprise, didn’t bother me: This is standard in most serialization systems.
– So we go on a quest to create a GUID…

GUID1:

– class Door : ISerializeCallback { Door otherDoor; public string guid = Guid.NewGuid().ToString(); /* use OnBefore / OnAfter callbacks to store the guid of the other door / find the door from guid */ }

Unity inspector lists:

– if you add an item to the list, 2 things corrupt your data:
1. all existing objects are NOT MOVED, but are CLONED into new list. This breaks our GUID.
2. the new item is a carbon-copy clone of the old – so it ends up with the SAME GUID (ouch)

GUID2:

– class Door { [SerializeField]private string _guid = Guid.NewGuid().ToString(); }
– now the inspector no longer clones the guid … BUT … instead it sets it to null.
– it seems to run the constructor, then use serialization to delete all values it finds

GUID3:

– class Door { private string _guid = Guid.NewGuid().ToString(); public string serializedGuid; /** use serialize callbacks to maintain serializedGuid */ }
– Disable the Editor’s list-renderer: it has at least two major bugs that corrupt data. Use the UnityEditorInternal.ReorderableList.
– NB: ReorderableList – with no customization – does not have either of the two bugs I saw with built-in Inspector’s lists.
– NB: as a bonus, with RL, we can avoid the “run constructor, delete all data, deserialize, reserialize” cycle, and directly create a new, blank instance with a safely generated – FRESH! – Guid.

Ctrl-D in Editor:

– breaks this, because we have no idea if a deserialize event comes from “ctrl-d” or from “read back from disk” (or from a prefab instantiating into the scene).

GUID4:

– class Door { public Room serializedRoom; private string _guid; /** use callbacks to peek into the serialized room, and use the guid as a “local ID within this room” */ }
– Because we’re now leaning on Room (which is a GameObject) to provide part of our GUID, in theory we don’t care about prefab/ctrl-d/etc — the code inside MonoBehaviour will automatically separate-out those cases for us.

Work with everything except prefabs, I think

– eventually gave up, removed the GUID completely, and changed game design to only allow ONE door to connect any pair of rooms. Yes, I was desperate!

THIS WORKS! Until you restart Unity:

– restarting unity causes this to deserialize on a different thread, and now you’re NOT ALLOWED to peek into the serialized room. You cannot use it as a substitute ID. You get crashes at load-time).
– …apart from that, this works fine. We have a solution that worked for ctrl-D, for prefabs.

GUID5:

– class Door { public Room serializedRoom; private bool _isUnityStillOnBackgroundThread; /** use the bool to say “deserialize happened but the data is NOT VALID, DONT RUN ANY METHODS” */ }
– …also use an AutoRun script with [InitializeOnLoad] and “EditorApplication.update += RunOnce;”
– …the autorun script waits for Unity to startup, then goes and Finds all objects, and finds all Rooms, all Doors — and does the fixup.

Fail, but can’t be debugged:

– I have no idea why this failed. It appeared perfect. Simply moving code that worked inside the deserialize (but crashed because it was run on “wrong” thread) out into the post-launc RunOnce method … silently fails. No errors, but no data.
– NB: this is impossible to debug, because we can’t even call ToString() on the deserialize method :(.

Conclusion

Give up. Make 10,000’s of Component instances instead. Waste memory, kill performance (especially at runtime: imagine how bad the AI’s going to be iterating over this!) but hey – IT WILL WORK. Because it leans on the built-in hacks that MonoBehaviour has had for years (which we’ve all been using millions of times a day without realising / appreciating ;)).

Categories
Uncategorized

Upgrading your Makerbot Replicator2 – 2014

3D printers are almost unique as a product: they can upgrade themselves. The Rep2 is one of the most popular/successful “production ready” printers out there. This post looks at what to do when you get a new one to upgrade it to the latest, bestest it can be.

Categories
games design programming Unity3D Unity3D-tips

Debugging A* Pathfinding in Unity

I needed fast, efficient, … but powerful, adaptable … pathfinding for my hobby project. My minions have to fly, walk, crawl, teleport, tunnel their way across a procedural landscape. Getting to that point has been tricky, but the journey’s been interesting.

We want something that intelligently routes creatures around obstacles, and picks “shallow” routes instead of scaling cliffs (or vice versa for Giant Spiders etc). Something like this:

Screen Shot 2014-08-10 at 20.09.36

Categories
iphone programming

OpenGL ES 2 – Video on iPhone in 3D, and Texture-Map sources

This is a blog post I wrote 6 months ago, and my life got too busy to finish it off, finish testing the code, improving the text. So I’m publishing this now, warts and all. There are probably bugs. There are bits that I could explain better – but I don’t have time. Note that the code is ripped from apps where I ACTUALLY USED IT – so I know it does work, and works well!

In brief:

  1. Using different “sources” of textures in OpenGL, not just images!
  2. Using CALayer’s as a source — allows for video in 3D!
  3. Using “Video straight from the video decoding chip” as a source – faster video!
Categories
amusing games design programming Unity3D

Rift + Sensor = Holodeck: VR nirvana?

Two things arrived in the post today, on the same day. (incidentally, one via FedEx, which was great, and one via UPS, which was dire – and gave my package to a stranger even though I was in the building WAITING for them to arrive).

Here they are, side by side:

IMG_20140731_185311small

Categories
android

Review: good SMS apps for Android

Why do we need this?

In a bizarre move, Google deleted the perfectly good SMS app from Android. Yeah. Hmm. Well, read this TechRadar piece for some thoughts on that.

Sadly, Google’s corporate policy is that the consumer is always wrong: you’re not allowed to simply “use the app I already had, that worked great”. Time for a trip to the Android App Store…

I tried:

Quick review of each

TextSecure

  1. does what it’s supposed to: show all conversations, send texts
  2. uses the “standard” view of SMS that we’re all accustomed to

…Deal breaker

  1. there’s no widget. Without a widget, you can’t get your phone to show “at a glance” new and recent SMS texts on the home screen / dashboard

Evolve SMS

  1. has a widget that works

…Dealbreakers

  1. enormously unpleasant “forced swipe” control system. I’m not sure why. Maybe: “Facebook did it, and it sucked, so Facebook stopped. But we want to be Facebook, so let’s copy their failures!”
  2. the back button is actually broken. This is a core feature of Android, one of the biggest improvements compared to iPhone. And Evolve broke it. (Sad face).
  3. the widget can’t be resized. Fixed size widgets are a real pain – you can’t place them where you want, cant put the things you want on same screen, can’t control the info displayed

HelloSMS

  1. basically works

…Dealbreakers

  1. stupid forced-swipe control (see above)
  2. On first start, requires you to swipe in wrong direction
  3. no widget

Go SMS Pro

  1. has a widget!
  2. basically works, but ugly

…Dealbreakers

  1. The widget WILL NOT DISPLAY incoming/recent texts. Instead it displays ONE text, and you have to hit buttons to “scroll” the widget to next / previous text. Wat?
  2. The app hangs if it’s not your “default SMS app”: you type something, it hangs. No other app had this problem, they all did a popup explaining, including a single-tap “fix this” button.

chompSMS

  1. has a widget
  2. looks really nice

…Dealbreaker

  1. The widget … is simply “an ugly resized version of the app icon” … and it does nothing. Seriously, a developer chose to add this feature, and implemented … nothing. Wat?

Summary / Winners

TextSecure is a perfect recreation of ” an SMS app that just works, the way its supposed to” … Apart from the lack of widget (essential!). It even has Apple iPhone style “free text messages to other users of the app”. If they’d fix that missing widget, it would be worth paying for…

chompSMS is very much like TextSecure, perhaps slightly prettier (personal preference). But the broken widget is just as bad as TextSecure’s, maybe worse. And it lacks the “free SMS” mode and “secure SMS” modes of TextSecure.

Evolve has the only working widget (essential!). But … you’ll frequently exit the app unintentionally when you hit the back button. And it’s unusable unless you like “swipe all the time to control UI instead of using the back button” behaviour.

Final thoughts

The rest … are not winners. I’m using TextSecure for now. When people say “people on Android don’t buy stuff”, partly it’s because the apps are incomplete: most of these apps haven’t been fully developed (how can you have a broken widget? Why did you launch without a widget? etc).

NB: as a developer, I can attest that “adding a widget” is very easy. It’s stressful the first time, and then you read the docs and examples, and realise “wow! this is going to be super quick to implement!”.

Categories
computer games dev-process games design programming Unity3D

World-exploration game, done differently

Inspired by Markus / @notch, and how he got MineCraft going in the early days, I’m live-prototyping a game idea I’ve been thinking about for ages. It’s about exploring a landscape … where cities affect dungeons, and dungeons affect cities.

(this is stress-relief for me, an “evenings and weekends” project. By day, I’m helping Schools teach children to program, but that’s HARD (no investors, lots of costs – at the moment, I get paid nothing))

Play in web browser here (very early prototype!)

Screen Shot 2014-07-25 at 12.31.23

July 2014

Current build focusses on the “City building” interface. Initially, you won’t be building cities, you’ll be building small camps / trading forts, etc. So this lets me play with the interface, the scale, the rendering, etc. Make sure it’s fun.

Create something – but take screenshots! Because there’s no “save” yet. Super-early prototype.

Long term gameplay

  1. Explore a huge landscape in FPS
  2. Any location, “create a camp”, and it switches to the isometric view you see in current demo. Build yourself a home/fort/etc.
  3. Fast-travel between locations, but this triggers “random encounter” events … or run between locations manually.
  4. Turn-based / DungeonMaster style dungeons are randomly generated near to each camp. Explore the dungeons for resources and to level-up.

Unlike e.g. Skyrim … when you find an interesting location, you can’t fast-travel to it. You have to build a camp next to it, and fast-travel to that. But your camp can be overrun/destroyed/stolen while you’re away.

So … you’ll be building (and maintaining) a lot of bases around the world. I want to be sure that base-building is easy and fun, even after you’ve done it lots of times already, before progressing with the rest!

(I’m trying to make it “repeatably fun” by having the landscape HUGELY affect your base design)

Categories
server admin

Webmail on your Debian server: exim4 + dovecot + roundcube

2015 UPDATE: I discovered that dovecot now uses MUCH longer passwords than it used to, and the database tables I’d found online WILL FAIL to authenticate (they truncate your passwords!). Fixed below

95% of linux configuration on Debian servers is simple, well-documented, well-designed, easy to do, with only a tiny bit of reading of docs.

Sadly, “making email work” is most of the 5% that’s: nearly impossible, very badly designed, badly packaged/documented. This OUGHT to take an hour or two, in practice it takes ONE WEEK to setup. WTF? In 2014? Unacceptable!

So I took several incomplete/broken guides, dozens of pages of help and advice, and synthesized this complete, step-by-step guide. This should get you the webmail you actually want (!) in an hour or less.

Categories
entrepreneurship marketing and PR startup advice

Your Pricing Models dictate your business success

Many businesses underestimate the power of a clever Pricing Model. I’m selling a new product at the moment (we’re helping schools teach children to program), so pricing models occupy a lot of my head right now.

Startups are so unsure of what model to use that they often say “anything, so long as we get sales”. They usually focus on simplicity (with a “new” product, a complex pricing model can tip people over the edge and make them “give up” on buying).

Which is fine, but a cunning pricing model can work wonders.

Categories
programming Unity3D Unity3D-tips

How to tidy your Unity code by putting it in a DLL

The importance of Re-use

Here’s a story that may sound familiar:

You downloaded Unity, watched some tutorials on YouTube, and had a physics “game” running the same day. Excited, you started writing the game you’ve always wanted to make. Possibly – bitten before when trying this with GameMaker etc – you thought to organize your source code: folders, subfolders, logically-named scripts, etc.

Fast-forward a few months, and you have 50 scripts in 40 sub-folders, some of it re-usable, some of it hardcoded for your game. Hoooo-Kayyyy… Well, it’s not too bad. And then a new opportunity comes along – a paid contract, a game-jam, a collaboration with a friend – and you want to re-use some code from your main project. You look at the folder structure, you look at how intertwined it’s all become … and you weep.

Without re-use, what seemed like an “easy” project becomes just a little too much work, and you never finish it. Back to square one :(.

Code re-use in Unity

There are five major aspects to code re-use when making Unity apps. Most of these are shared with general programming, but these are the ones I’ve found *especially* important when doing Unity development.

Good names

The best way to get good at naming things in a program is to focus on “what makes a bad name”, and “Don’t do that”. e.g.

  • If you have to open a Script to remember what it does … it has the wrong name.
  • If you keep typo’ing the script when referencing it in other scripts … it’s the wrong name
  • If your script is more than a thousand lines long … it’s the wrong name AND you’ve put too much junk in there; split it!
  • If you can’t find a script, because you can’t remember which folder it’s in … the folder name is wrong, AND the script name is wrong (should have been a name that forced you to put it in the right place first time!)
  • …etc

Renaming scripts in Unity is a minor pain: you rename it, then you have to close the file in MonoDevelop, re-open it, and (assuming it was a C# class) rename the class in source-code too. (I keep hoping latest Unity will do this automatically, but I’m a version behind at the moment).

We need Sub-folders. Lots of Sub-Folders

… you can never have too many. Give them good names, though!

De-couple your code

Ah, now it gets tricky. The art of decoupling takes much practice to master.

Decoupling is why C# (and Java) has the “interface” keyword. The concept is much easier to understand after you cocked it up, written code you can’t re-use, because everything’s too inter-dependent.

“I can’t just copy/paste that script to my new project, because it references 3 other scripts. Each of which … references another 12. ARGH!”

Unity itself doesn’t use Interfaces (though it really ought to!) – and you have to use a little ingenuity to use them yourself (Google it, it’s only a few small caveats). But C#-interfaces simply give you a compiler-compatible way of decoupling: you have to design your classes as decoupled to start with. Again, google this and ask around – it’s too big a topic for me to do justice to here!

Package your code, so you can re-use it

Libraries. This is why The God Of Programming invented Libraries. So, how do you do a Library in Unity?

Libraries in Unity: the easy DLL

There are two kinds of DLL’s:

  1. Real DLL’s, as used by Real Men, who write all their code in C++
  2. Fake DLL’s, as used by the rest of us, who just want an easy life so we can focus on making our game

A DLL is a great way of packaging code – it’s a very widely-used standard. So, Unity uses DLL’s for this (good move) – but if you google “Unity make DLL” you’ll get distracted by the huge complexity and depth of C++/Unity integration, and you don’t need any of it. Instead, you’ll be doing “DLL light”, which is easy.

But, as with most Unity features, it’s almost entirely undocumented. And, out of the box, it will fail. For bonus points, Unity will give you completely the wrong error message when it goes wrong. Yay!

Step 1: write a Unity script in Unity

Do something simple. I wrote a class that makes random numbers, following XKCD’s advice:

[csharp]
using UnityEngine;

/** In Unity 3, you cannot have namespaces. So comment out this next line. Unity 4 is fine */
namespace MyTestDLL
{
public class DLLClass
{
public static int GetRandom()
{
return 4;
}
}
/** In Unity 3, you cannot have namespaces. So comment out this next line. Unity 4 is fine */
}
[/csharp]

Make a second script that uses that first one, e.g.
[csharp]
using UnityEngine;

public class TestScript : MonoBehaviour
{
void Start()
{
print( DLLClass.GetRandom() );
}
}
[/csharp]

…attach it to a GameObject, check it works.

Step 2: follow Unity’s docs on creating and using a DLL

You’d think this would be enough, but it isn’t. However, the docs are simple, direct, and I found them easy to follow.

So http://docs.unity3d.com/Documentation/Manual/UsingDLL.html = read this and do what it says

NB: they write a slightly more complex script to use than mine, with but whatever. The idea is the same.

Step 3: Use the namespace, Luke. And Interfaces. And …

Now that your DLL is compiling/building in MonoDevelop … you are no longer stuck with Unity’s arbitrary rules and restrictions! The world is yours!

(so, even in Unity 3, you can now use the namespace. Which makes it MUCH easier to keep your code well-organized ;))

Step 4: What about the [square brackets]?

These Just Work ™ exactly as they did in Unity scripts. e.g.

[csharp]
using UnityEngine;

namespace MyTestDLL
{

/** Hey! Look! Unity editor-features … coded outside of Unity */
[ExecuteInEditMode]
[System.Serializable]
public class DLLClass
{

[/csharp]

Step 5: Editor extensions, editor scripts, editor GUIs, etc

This is where it breaks. If you had any Editor scripts (which, in Unity, MUST be stored in the “Editor” root folder, or one of its subfolders), you can include them in your DLL – but they won’t work.

Worse, when you trigger them (e.g. by selecting a GameObject that did custom editor rendering), you’ll get:

Error: multi-object editing not supported !

…at least, you do in Unity 3.x. Fixed in 4.x, I suspect? But I haven’t gone back to try it since I fixed the bug :).

There is some mumbo-jumbo on the internet (and Unity forums) about complicated workarounds, notably courtesy of AngryAnt (with a Jan 2014 post here, with some extra info worth reading but NOT required!). But these are long-since outdated and unnecessary. The fix is very simple: we must create TWO DLL’s!

  1. DLL #1: the one we already had
  2. DLL #2: will contain ONLY the editor-scripts, and we’ll drag/drop it into Unity’s “Editor” folder.

This is extremely logical, simple, and easy to remember. And it works beautifully! But .. how?

Step 5a: Upgrade MonoDevelop project to output not one, but two, DLL’s

First, right-click on the top-most item in MonoDevelop’s “Solution” panel, and select “Add New Project…”:

Screen Shot 2014-05-24 at 20.54.53

As you did earlier, choose “Library (C#)”. I recommend naming this “SomethingSomethingEditorScripts” (where “SomethingSomething” is your library name, which you used for the first DLL).

Second, you need to edit the References (as you did with first DLL), and this time repeat the steps and add ALL of:

  • UnityEngine.dll
  • UnityEditor.dll
  • AND: instead of the “.Net Assembly” tab, use the “Projects” tab and select your main DLL/library. It should be the only option

That gives you something like this:

Screen Shot 2014-05-24 at 20.58.22

…see how I have two “projects” in MonoDevelop, one which just uses normal Unity stuff, the other which additionally uses Unity Editor stuff? And the second one “references” the first, so it can see/use/create the classes and methods from the first one.

Step 5b: Put the DLL’s in different places

Build, and find the output files. The first project/DLL will still only be making one DLL, but the folder for the SECOND project/DLL will conveniently build BOTH projects and contain BOTH DLL’s.

Make sure you put one DLL “anywhere except Editor” and the other one “in Editor, or a subfolder of Editor”.

Finally, create some GameObject’s, open up the DLL’s in Unity’s Project view (expand the triangle) and drag/drop the Scripts onto your objects as desired. Click on them in the Scene view, and all your OnGUI, OnGizmos etc methods should run exactly as normal.

Step 6: Rejoice!

Now you can share your code with other Unity projects simply by drag/dropping the 2 x DLL’s into a new Unity project. BOOM!

Beautiful! Easy, simple, impossible-to-screw-up ;). That’s how I like my code re-use…