Mark Gilbert's Blog

Science and technology, served light and fluffy.

Giving the game a voice – TextBoxDribble

One day on a car trip, CJ and I were brainstorming about the algebra game, and my two daughters got into the act.  The three girls started working out a storyline for the game, and how there should be a guide of some sort that leads you through the levels.  The girls did some sketches, and I quickly threw one in to see what it would look like.


A lot of the game is (we think) intuitive, or is explained to you in the tutorials.  However, there are a handful of messages that can appear during gameplay, mostly around telling you when you tried to do something invalid (like applying an operation to only one side of the equation).  I thought it would be cool to have this wizardly-looking mentor fellow “speak” those feedback messages to the user.  To make that look a little more convincing, I wanted the message to “dribble” in, one word at a time, instead of having the full message appear over the image, to mimic someone speaking them.


To do that, I wrote a script called TextBoxDribble.  As the name implies, this script will make the message you assign to a textbox appear to dribble in.  Here is the script, in its entirety:

using UnityEngine;
using UnityEngine.UI;

public class TextBoxDribble : MonoBehaviour

[Tooltip(“Must be greater than 0; defaults to 1”)]
public int FramesBetweenEachWord = 1;

private string _PreviousValue;
private string _NewValue;
private string[] _Words;
private bool _ShouldWatchForChanges;
private bool _ShouldDribbleTheWordsIn;
private int _WordIndex;

private void Start()

this._ShouldWatchForChanges = true;
this._ShouldDribbleTheWordsIn = false;
this._WordIndex = 0;
this._PreviousValue = this.GetComponent<Text>().text;

        // Make sure FramesBetweenEachWord is always something valid;
if (FramesBetweenEachWord <= 0) { FramesBetweenEachWord = 1; }


void Update ()

if(this._ShouldWatchForChanges && !this._PreviousValue.Equals(this.GetComponent<Text>().text))

this._ShouldWatchForChanges = false;
this._NewValue = this.GetComponent<Text>().text;
this.GetComponent<Text>().text = “”;
this._Words = this._NewValue.Split(‘ ‘);
this._WordIndex = 0;
this._ShouldDribbleTheWordsIn = true;



if (this._WordIndex < this._Words.Length)

if(Time.frameCount % FramesBetweenEachWord == 0)

this.GetComponent<Text>().text = string.Format(“{0} {1}”, this.GetComponent<Text>().text, this._Words[this._WordIndex]);



this._PreviousValue = this.GetComponent<Text>().text;
this._NewValue = “”;
this._ShouldDribbleTheWordsIn = false;
this._ShouldWatchForChanges = true;






The script’s Update() method has two main pieces.  The first conditional looks for changes to the textbox .text property.  When the textbox is assigned a new value, the script pulls it out, breaks it into an array of words, clears the textbox, and sets _ShouldDribbleTheWordsIn to true.

That signals the second block to go into action.  This block begins to reconstruct the new message, one word at a time.  Once the entire original value has been assigned, it goes back to watching for new changes.

The user can control how quickly the words appear through the public FramesBetweenEachWord property, which gets exposed in the Unity editor.  The name, hopefully, explains how it will work – the higher the value, the more time passes between each word getting appended, and the slower the overall phrase will come in.

October 9, 2017 Posted by | Game - Algebra, Unity | Comments Off on Giving the game a voice – TextBoxDribble

Drag-and-drop, Event-ually

I mentioned in my previous Unity post that the logic powering the dragging and dropping on the equation screen was not straightforward to develop.  I had multiple false starts looking for a pattern that could support everything I needed it to:

* Dragging operations out of the OperationsTray and dropping them onto a domino to place it
* Dragging operations out of the OperationsTray or a domino, and dropping it onto the screen to delete it
* Dragging operations out of a domino to place it into another domino
* Dragging dominos to merge them with another
* Etc.

What I finally landed on was evaluating the Input.GetMouseButtonDown, Input.GetMouseButton, and Input.GetMouseButtonUp methods in the EquationScreenController.Update event handler.  (“Mouse button” here covers both clicking a mouse button as well as touching the screen with your finger.)  These methods return true when the user first clicks the mouse button to grab something, holds the mouse button down to move it, and then releases the button to drop it, respectively.

Once the user grabbed something, I needed logic to determine what they grabbed and were now dragging.  As they were dragging it, I had to refresh the UI so that the thing being dragged would actually track with their finger.  Once they dropped it, I had to evaluate if they dropped it on a valid spot or not, and do something in both cases.

My first working iteration of this required pages and pages of conditional logic – very ugly and hard to debug.  I needed a better way.  Luckily, history repeats itself – or is it “recurses”?

Years ago, when my colleagues and I were playing with the Microsoft Kinect, we started a project where the user would dress a paper doll on screen.  The user would “pick up” some article of clothing, move it over the doll, and then “drop it”.  “Pick up” in this game translated into “hold your hand over the article of clothing on the screen for a second or two until you convinced the software that you wanted THAT one”.  At that point, it would pop it off of the “wardrobe” and being to track with your hand.  “Drop it” translated into the user pushing their hand toward the Kinect, as if he or she were pushing a piece of paper onto a corkboard.

What that app taught me was the value in custom events.  The Kinect reports the three-dimensional position of 20 different joints for the user, 30 times a second.  I ended up writing a “manager” class that would translate the raw data coming off the Kinect into a series of events being raised – specifically things like hover, pick up a piece of clothing, drop a piece of clothing, etc.  That translation layer greatly simplified writing, and especially debugging, the rest of the app.

I decided to go the same route here.  Here is a slightly simplified version of the new EquationScreenController.Update() logic:

public void Update()

if (Input.GetMouseButtonDown(0))


else if (Input.GetMouseButton(0))


else if (Input.GetMouseButtonUp(0))




The DragDropManager.Evaluate… methods would translate the raw UI input into a series of events to be raised:

  • OperationPickedUp
  • DominoPickedUp
  • OperationMoved
  • DominoMoved
  • DroppedOnNothing
  • DroppedOnDomino

My EquationScreenController, then, would handle those events and do all of the necessary UI steps.

This structure allowed me to not only abstract the messy details of the translation away, but it broke up the monolithic Update() method I had going into smaller, and much easier to debug, methods.

As a bonus, the refactored structure made it possible to unit-test the three DragDropManager methods.  I could set up various scenarios, and verify that the proper events were being raised given that input.

October 2, 2017 Posted by | Game - Algebra, Unity | Comments Off on Drag-and-drop, Event-ually

Staying on top of things

One of the first things I tackled for the algebra game was the drag-n-drop logic for the equation screen.  The path to that logic was not straightforward at all, and I’ll go into more detail about that in my next post.  One of the first oddities I encountered testing this was that the gameobject I was dragging didn’t always appear on top of everything else.  Sometimes it looked like my operation, for example, was sliding behind its siblings.

On the equation screen, there are two types of things that are draggable – operations:


And the terms of the equation, which appear in a UI control CJ dubbed “dominos”:


Initially, I found that the operation/domino being dragged would appear behind the operations/dominos to its right, along with several other controls rendered on the page.  After a bit, I realized what was happening.  Unity determines the z-order (depth) of the gameobjects on the screen in the order they appear in the Hierarchy tab.


Things that appear higher up in the hierarchy will be rendered visually behind things further down in the hierarchy.  When I populate the list of operations, I add them one after another to the OperationsPanel, which meant that the first one would appear visually behind the second, the second behind the third, and so on.

To solve this, as soon as I start dragging an operation or a domino, I re-parent it to the top-level canvas object, and then I make it the last sibling of the canvas:

this._ParentCanvas = transform.root.gameObject;

Since I can only drag one gameobject at a time, these two steps guarantee that the item being dragged will appear below every other gameobject in the hierachy, which means it will appear visually on top of everything else.  When I drop it onto a new container, I re-parent it to that container, which effectively resets it to the “proper” place in the hierarchy.

September 25, 2017 Posted by | Game - Algebra, Unity | 1 Comment

3D-Printed Desk Fan Base

I’ve had a desk fan at home for years, but I was never happy with the base.  It was just too deep:


That large ring pushed the fan too far out from the wall, so it was taking up way more room than I thought it should.  The fan’s existing base attached with two screws, which were easily removed:


A little while ago, my brother got a 3D printer, and offered to print stuff for us.  All we needed to do was send him the file.  I decided it was time to try my hand at this, and see if I could come up with a better base.  The printer could handle things up to 5.5” x 5.5” x 5.5”.  That was more than enough to accommodate the height of what I had in mind, but to make the new base stable, I figured it would need to be close to the width of the fan, which was more like 8 inches.  Even if the printer could print something that large, I didn’t want to use that much filament printing a solid block of plastic.  I dug around my junk box, and found these:


These were bendable metal straps that came with a swingset anchor kit, but they were too small to use with our new swingset.  If I turned them up on their edges, though, they could become the legs of the new base.  With that idea in hand, I fired up SketchUp to generate the 3D drawing.  Fast forward 3 hours, and I arrived at this:


I exported this as an STL file, and emailed it to my brother.  Fast forward several hours again, and we get this:


The top is solid.  The bottom has two channels that I hoped would allow me to insert the metal straps:


I started by drilling out two holes that would hopefully match the fan’s base.


They are intentionally offset because I wanted the fan to lean back a little.  Next, I cut a piece of 12-gauge solid copper wire, and bent it into a U-shape:


The holes were just large enough to accommodate the wire, so friction would do most of the work of holding it in place:



Next it was time to insert the new legs.  I bent the metal straps to match the V-shaped bends in the base, and worked them in gently:


I was most worried about pieces of the plastic base snapping off if I pushed it too hard, but it remained solid. Here’s the assembled base:


I re-attached the base to the fan, and bent the wire over to make doubly-sure it wouldn’t pull out accidentally:


The new base didn’t look too bad:


And it was significantly less deep than the original:


I did notice the fan felt like it would fall backward a little too easily now, but another bend to the rear legs solved that:


All in all, a resounding success.  3D printing got a new fan today.


July 4, 2017 Posted by | Maker Life | Comments Off on 3D-Printed Desk Fan Base

Unit-Testing in Unity

CJ and I are collaborating to build an app that teaches you how to solve single-variable algebraic equations like this:

2x – 4 = 16

Our target audiences are kids and teachers, so it was obvious to us that this would be a mobile app.  For me, the choice of development platform was also a no-brainer – Unity:

  • Katherine and I had tinkered with Unity a while ago, so I was already familiar with it
  • It can generate binaries for every platform we’re considering, and then some (XBox or PS4 anyone?)
  • One of the primary programming languages supported was C#
  • Unity integrates with Visual Studio (you can also use MonoDevelop, but if you know and love VS, why?)
  • Unity has a flourishing user community
  • I could get started for free

One of the very first things I figure out with any new development language / platform / IDE is how to build unit-tests with it.  As it turns out, Unity has a built-in test-runner based on NUnit (yet another point of familiarity for me).  The runner is available under the Window menu, but normally I leave it docked on the right side of the IDE.


Now the next step was figure out WHERE my tests should actually live.  After a little digging I found an article on the Unity Test Runner.  The test runner has two modes – Play and Edit.  I started with Edit, and (as the article shows), there was a button for “Created EditMode Test”.  I clicked it, and it created a folder called Assets/UnitTests/Editor.  I tried renaming and moving the folders in that string, and kept on eye on the test runner – would it find my test if I put it in a folder called this?.  As it turns out, the “Editor” folder has special meaning for Unity.  I settled on a folder structure of Assets/Editor/UnitTests (inverting what Unity created by default), so I could add other Editor scripts later if I needed.


Now that I had the basic structure, it was time to get down to business, and start writing the logic for the game.  Fast-forward several weeks and 450+ unit tests later, and I have a few observations about unit testing in Unity.

The integration between the Unity IDE and Visual Studio is fairly seamless.  I can add a new test in the latter, switch back to the former (where it kicks off a compilation in the background automatically), and see it appear a second or two later.  In Studio, there is a preset button for attaching to Unity, allowing me to debug through my test and business logic easily.  The one minor quirk is how Unity reports compilation errors – subtly, at the very bottom of the Unity UI:


This stung me a couple of times – I would make some typographical error, miss this clue that my new code wasn’t actually compiling, and re-ran my unit tests expecting a change, only to find that the same test was failing because my new code wasn’t actually being used yet.  To avoid this, I now do an explicit compilation in Studio, and let Studio throw up the errors and warnings I’m used to seeing.

As a whole, the test runner does its job reliably.  One thing I’d change, though, is how it reports the current state of the tests.  If you’ve already run your test suite once, and want to run it again, Unity doesn’t clear all of the green (and red) flags for the already-run tests.  Unless something switches from red to green or vice versa, you really don’t have any indication which test is being run at the moment, how far it is through the suite, etc.  There IS a progress bar that appears while the tests are being executed:


And once that disappears you know it’s done, but I’d prefer the test statuses to be cleared before each run so I can watch it work through the suite again, fresh.

I’ve also noticed that the tests run much faster if you keep the focus on Unity the whole time.  More than once I would kick off a series of tests, and switch to some other window while they ran, and found my tests were still running long beyond when they should have (I’ve seen suites take 2-7 times longer to complete this way).  Again, a relatively easy issue to avoid – don’t switch away from Unity while the tests are running – but an odd one.

Overall, I’m very happy with my choice of Unity.

June 18, 2017 Posted by | Agile, Game - Algebra, Unity, Visual Studio/.NET | Comments Off on Unit-Testing in Unity

Moving back from the Cloud

Back in August I mentioned moving my critical files to the cloud so I’d have them available from both home and at work.  At the time I selected OneDrive to be my cloud storage provider, and mapped a network drive on both machines so all of my shortcuts would work.

While it solved the problem of losing a very tiny thumbdrive, it introduced some serious lag to Tasks, my custom-written task management app.  Every time I needed to create a new task, update an existing one, or reprioritize the things on my todo list, there was at least 2-3 seconds (and sometimes a lot more) delay in committing that change to OneDrive.  Very soon after I began using OneDrive like this, I started to think through how I could hide more of this lag in the background of Tasks so it would be less noticeable.

Then last week I started getting permission errors from OneDrive.  After some tinkering, I found that I could no longer even drag files into the drive letter I had mapped, or directly modify files through the drive letter, without it complaining about permission issues.  If I did everything through the browser, it was fine, but not through my drive letter.

I spent a night troubleshooting it, and then I pulled out my old thumbdrive as an interim solution.  I went a week like that, hoping that Microsoft would sort out whatever it was they had changed.  This weekend I retested it, and found it was still misbehaving.  I took another look at using Google Drive, but apparently you need some third-party software to map a drive letter to it, so I abandoned that idea.

That’s when I took a hard look at what I had in the cloud, and found that I either didn’t really need access to those files at work, or came up with alternatives (like the occasional email to myself).

Today was my first day 1) not carrying a thumbdrive, and 2) not relying on the cloud for anything relating to my todo list.  To my surprise, I barely noticed the difference.  I felt just as productive, and no longer experienced any of the lag I was seeing with saving things to OneDrive.  I still use Tasks at home, though, but the files are now stored on my local server, rather than in the cloud, so again – no thumbdrive and no lag.

Am I annoyed with OneDrive for ceasing to work?  A little, but being forced to give it up allowed me to ditch the lag at the same time, so I won’t be annoyed for long.

January 30, 2017 Posted by | Tools and Toys | Comments Off on Moving back from the Cloud

Dropping a mic – and picking up another

In the middle of our most recent podcast we had a major technical failure.


The microphone Katherine, Lucy, and I have used for the first 32 podcasts finally gave up the ghost.  To be fair, it had broken a couple of times before, and I had apply liberal amounts of glue to piece it back together.  This time, though, half of the audio tracks Lucy and I recorded had too much static to be usable.

So, we said goodbye to Computer Associates, and hello to Tonor.


This is a Tonor 3.5mm Cardoid Condensor Microphone.  We recorded all of the tracks for Episode 33 with the Tonor, and we think it sounds at least as good.  Let us know what you think!

January 11, 2017 Posted by | Podcast, Tools and Toys | Comments Off on Dropping a mic – and picking up another

Science & Technology Podcast, Episode 33: String Shooter

Mark and Lucy build a machine that shoots string, and lets them play with waves:

January 10, 2017 Posted by | Podcast, Science | Comments Off on Science & Technology Podcast, Episode 33: String Shooter

Science & Technology Podcast, Episode 32: Summoning Thor’s Hammer

Where we build a second prototype of a flying Thor’s Hammer that you can summon:

September 23, 2016 Posted by | Podcast | Comments Off on Science & Technology Podcast, Episode 32: Summoning Thor’s Hammer

Moving to the Cloud

For many years, I’ve carried what you might call my life’s work on a thumb drive.


This 4GB drive held sample code I put together, documents I’d written, all of the data files for Tasks, my personal log – everything.  It was getting backed up every night to the cloud, but the primary source of truth was always this drive.

Then a couple of months ago I got a new laptop at work, mostly because I found myself needing to travel more frequently – whether it was down the hall to a conference call, or out of state for an onsite.  Since this was my primary machine, I would faithfully plug this thumb drive into the side.  However, it would stick out so far I was always afraid I would snag it on something, and bend or otherwise damage it.

So I replaced it with this tiny SanDisk.


My thinking was that it would keep a low-enough profile that I wouldn’t need to worry about it catching on anything.  I wasn’t wrong there, but moving to such a small thumb drive had an unexpected consequence.  I had to pay extra attention to where the thing was when it wasn’t a) plugged into my computer, or b) zipped up in my laptop case.

In other words, it was so tiny I was in danger of losing it every time I put it in my pocket. 

That thought increasingly nagged me.  Then one morning I walked out to my car and it fell out of my pocket when I retrieved my keys.  When I got to the car, I patted my pocket to make sure it was there, and it wasn’t.  I hurriedly retraced my steps, and found it in the garage.  I never even heard it hit the ground because the noise from the garage door opener masked the impact.  I resolved then and there to find a better solution.

I took a long hard look at what was on the drive, and what I actually needed with me:

  • I was keeping several software installers and configuration files on that drive.  Those were easy to move to my home server.  If I actually needed them at work, I could always wait a day, and bring in what I needed the next morning.
  • The next batch of files comprised the bulk of the contents of the drive.  They were files I rarely dipped into, and more times than not was actually at home when I did.  Those also got moved onto my home server.
  • Then there were a handful of files that I would actually need at work.  These were rarely (if ever) needed at work, so those got left on my corporate user’s drive.

Then it came down to the files that I would needed regularly at both home and at work – the files that Tasks required, and my personal log.  I didn’t want to load those onto my phone because then I’d have to keep it jacked into my computer to access them.  I also discarded any "syncing" solution due to my previous bad experiences.

That left me with putting these files in the cloud.  Would it be possible to map a drive letter to a folder somewhere (a requirement to keep Tasks work as is), and let me access them from home or at work?  I looked at both Microsoft’s OneDrive and Google’s Drive, and as it turns out both allow me to map a local drive letter.  I ultimately went with OneDrive since I already had files up there from past projects. 

With these files in the cloud, I had completely weaned myself off of thumb drive.  I could now fire up Tasks at home or at work, and get to all of my project notes.  The biggest downside has been the lag – saving files to the cloud is substantially slower than saving them on my thumb drive.  I’ve started thinking about ways to modify Tasks to do its saving-to-the-cloud in the background, making it more responsive.

I have so far had one occasion where I lost a file update (memories of August 2009 came rushing back – see the links above).  I wasn’t sure what triggered it, but somewhere along the way one of my most critical project files got completely wiped out – a 0-byte was all that remained.  I had a relatively recent update, and only ended up losing a few hours’ worth of work, but as a result, I’ve tweaked my regular backup to pull these files down from OneDrive, nightly.

All in all, the move to the cloud seems to be working fairly well, and it certainly renders the question of "what do I do if I lose my thumb drive?" moot.

August 13, 2016 Posted by | Tools and Toys | Comments Off on Moving to the Cloud