Elegant Editor-Only Script Execution in Unity3d

Lately I’ve been doing a lot of Unity programming. I love how easy it is to develop editor tools for my designers and how seamlessly these tools tend to integrate with the runtime environment. My favourite feature is the [ExecuteInEditMode] attribute because it lets me write all kinds of funky real-time level generation tools. (Like extruding 3D meshes from 2D primitives!) But what this attribute sorely lacks is the ability to have code execute ONLY in edit mode, where performance isn’t such a big deal. By default code placed in the Update() method will execute both when the scene changes in edit mode AND during every frame of play mode, making it unwieldy for expensive operations like realtime mesh generation (or even a large number of tiny operations, like setting a renderer’s sorting layer).

Step 1: Execute Only In Edit Mode

Various hacks around the internet purport to solve this problem. Some suggest using conditional compilation directives like #if UNITY_EDITOR. This is helpful for platform-specific builds, but unfortunately code placed within these directives will still execute in the editor’s play mode (which is, of course, where 98% of testing happens). Another approach involves checking a global variable like Application.isPlaying before doing anything editor-specific, but this is less than ideal should you have hundreds of active scripts in your scene (the performance cost of calling Update() on that many components, even if that function contains only one boolean comparison, can add up surprisingly fast). I’ve also found, although I haven’t verified it experimentally, that isPlaying becomes rather unreliable when it mixes with big scenes, custom inspectors and ExecuteInEditMode scripts.

I now use a solution that makes use of both conditional compile tags and a little-known global variable in the EditorApplication class:

[ExecuteInEditMode]
public class CurveGenerator : MonoBehaviour {

#if UNITY_EDITOR
	void Update () {
		if(UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode) {
			this.enabled = false;
		} else {
			// editor code here!
		}
	}
	#endif
#endif

}

Here’s how this works. In edit mode, isPlayingOrWillChangePlaymode will always return false; thus, the editor-only code located within that else statement will execute every time Update() is called (generally every time the scene changes). In play mode isPlayingOrWillChangePlaymode will always return true, causing the MonoBehaviour to disable itself on the very first Update() and cease hogging performance beyond the first frame. (This is especially helpful when you’re trying to use the profiler to isolate script bottlenecks.) In compiled versions of the game the Update() method won’t even exist, saving us the trouble of having to disable it. The result of all this is that you can run horrifyingly-expensive setup code in edit mode that costs virtually no performance during play, which arguably is the entire point of an IDE like Unity.

Now, I know what some of you are thinking: ‘Why not do away with all this ExecuteInEditMode voodoo and simply write a custom inspector? It will never run in play mode and you can use SerializedProperties and GUILayout and all that magic.’ Well, here’s the thing: Custom inspectors act only on currently-selected Unity object(s). Suppose you had a bunch of prefab instances, some of which had overridden properties, and you wanted every single one of them to regenerate their content each time you modified the parent prefab? What if some of your generator scripts modify other generator scripts, and you needed those ones to be responsible for their own regeneration even when not a single one of them is selected (and therefore their custom inspector code is completely unloaded)? What if those scripts used prefabs? ExecuteInEditMode provides an understandable, reliable, and relatively efficient way to let scripts respond to any change in state from anywhere in the IDE. Inspectors will never do that for you.

Read more…

Lord Bafford’s Manor

Saturday night  3 AM. I’ve been feeling an irrational urge to play the new Thief. I could not tell you why. I’ve heard that the level design is very good. Sadly, I’ve also heard that the rest of it is a bland, soggy porridge of directionless conspiracy film tropes and cloying AAA panache; caught in the middle, in other words, its various stakeholders unable to decide whether to seek the tone of its predecessors or ape whatever marketing trends were big back when the project hit preproduction. I’ve seen first hand how this happens: The masters of coveted IPs are often better at policing the surface elements of a project (the plot; the art direction; the marketing) than they are at policing the videogame stuff. Thus as a developer you become fixated on pushing a reasonable game design through even if you’ve been ordered to make Garrett into a Vengeance-Driven™ Cool Videogame Anti-Hero™ with a Dead Girlfriend™ standing resolute against a Plague-Ridden Cityscape™. I confess my urge to Twitter in hopes someone will convince me not to buy the thing; @fengxii mistakenly assumes I was talking about my desire to play the original Thief, and implores me to give in. Hmm. That sounds like a better idea.

I’ve played Deadly Shadows before, but never The Dark Project. Its age doesn’t phase me. I pride myself on my ability to jump headlong into ancient videogames, and 1998 is hardly as far back as our medium goes. 800×600 on a high-res 16:10 monitor? Fine. Glaring mouse lag? Okay. Muddy late ’90s textures mapped onto Quake-era BSP trees? Perfect. I could fix all of these things if I wanted to, but that would destroy the original context. I find myself enamoured by Dark Project’s chunky walls, which feel more solid than the elaborate trickery we use today. Here there are no invisible collision volumes warding us away from some bit of twenty-thousand polygon street junk, placed more to afford realistic screenshots than to produce an actual physical environment. There are no normal maps to create the illusion of depth along its brick walls even if, in truth, they are flat. Dark Project’s walls are walls. You can touch them.

Read more…

The Cult of the Peacock

It’s easy to forget that at one time all videogames had manuals. I used to like reading manuals. Manuals were cool. Now, instead of manuals, we have interactive tutorials. They take about fifty times longer to produce, three times longer to consume, and players hate them so much that their highest aspiration is to become completely transparent. Currently I spend most of my waking hours developing them. It should come as no surprise that I hate them too.

This is a story about how these things happened. It’s sort of a companion piece to the article I wrote about Liz Ryerson’s Problem Attic in that it examines the reasons why games like that became unfashionable, how this is a bad thing, and what we might do to fix it. It’s a story about the history of interaction design both in academia and the games industry, as well as my experiences travelling through those spaces. It’s a story about how I got the kink in my neck, and the slow death of the videogame manual. It begins with a teapot and ends with a peacock. More than anything, though, it is about apotheosis. There are four parts. Shall we begin?

Read more…

Fashion, Emptiness and Problem Attic

Problem Attic is a game by Liz Ryerson that you can read about and play (for free!) on her website.

problem attic

Any designed work can be decomposed into two different kinds of features: Intrinsic features and extrinsic features. An intrinsic feature is something we judge to be a non-reducible atom of actual value that the audience wants and the work provides—that is, the work’s purpose—while an extrinsic feature is anything that exists solely to realize that purpose, providing no actual value in itself. To design something we must first decide which intrinsic features we hope to provide and then do so as efficiently as possible by devising and iterating on a set of extrinsic ones. Here is a quick example: The intrinsic features of a hammer include ‘delivering impacts to objects’ and ‘inserting/removing nails from rigid structures’, and to best realize these we might iterate on any number of extrinsic ones (such as the hammer’s shape, the materials of which it is composed, or its manufacturing cost).

A product, which is a special kind of designed work, has at least two intrinsic features. One is to perform the task for which it was made; the other is to convince you to buy it. (The next time you hear the phrase ‘ludonarrative dissonance’ ask yourself whether the dissonance you’re discussing might actually stand between ‘what marketing decided would generate money’ and ‘what the designers defiantly attempted to produce’.)

Iterations on a design’s intrinsic features are transformative; they change what the work is on a fundamental level by changing what it does. (A hammer that cannot deliver impacts to objects is no longer, ontologically speaking, a hammer; it has become something else.) Iterations on a design’s extrinsic features are merely ameliorative; they make it better at fulfilling its purpose without changing its nature. Thus we only value extrinsic features insofar as they improve a design’s ability to give us the things we actually want, and we are quite content to discard them as soon as we find more effective ones. Walmart would stop selling hammers if they could figure out how to to market telekinesis. Google would stop making iPhone apps if they could perfect the horrifying spider drones that burrow into your brain through your nasal cavity and telepathically communicate bus directions to you.

The intrinsic features of Art media like literature or film, unlike those of hammers and map APIs, are not easily reducible into language. Whereas to design a hammer involves finding ways of realizing features whose value is readily apparent, to make Art is to search for value lying beyond the edges of our understanding: To capture something we know is important to us even though we cannot quite say why. This is what makes ‘Art’ so famously difficult to define, and why we speak not about ‘novel designers’ or ‘film designers’ but about  the authors of these works. Authors are a specialized type of designer who work to realize feelings, concepts or moments; often they attempt to connect in some fashion with our shared humanity. We cannot fully express what their work is for because its value transcends understanding. Thus while conventional design undoubtedly remains useful as a means of iterating towards our authorial objectives (the language by which we communicate mood during a film, for example, is the product of very sophisticated design work) it tells us nothing about what our authorial objectives should actually be nor what our Art becomes when we realize them.

Videogames inherit a little from Art but mostly from product design, which has been kind of a problem for us. As an industry we put faith in the idea that there is intrinsic value in the games we develop, although we don’t think very expansively about what that could be; instead we abstract it, using ugly words like “content” as placeholders for value without ever proving that it truly exists. We then set about designing incredible machines that shuttle players towards these placeholders with extremely high efficiency, which as designers is really what we’re good at. We make the interface as usable as we can because players need it in order to learn the rules. We teach the rules very carefully because players need them in order to grok the dynamics. We shape our dynamics strategically because enacting them is what will stimulate players to feel the aesthetics. Somewhere at the core of all this, we suppose, lives the “content” players are attempting to access: That which we have abstracted away so that we could hurry towards doing safe, understandable product design rather than risky, unfathomable Art. In game design we enjoy paying lip service to aesthetics. What, then, shall we say are the aesthetics that we can package up into 5–60 hours of intrinsic value? Challenge? Agency? Story? Fun? Is ‘Mario’ an aesthetic? How do we stimulate the Mario part of the brain? Oh hey, wait, look over there! Someone is confused about what that UI indicator represents! TO THE DONALD NORMAN MOBILE.

The more time I spend examining my professional work and that of my peers in the games industry, the more I come to believe our near-sightedness has crippled us. We have avoided building sophisticated pleasures that demand and reward the player’s investment, preferring instead to construct concentric layers of impeccably-designed sound and fury over an empty foundation of which we are afraid and at which we can hardly bear to look. We gamify our games, and then we gamify the gamifications, so that many different channels of information can remain open all at once, distracting the player by scattering her attention across a thousand extrinsic reward systems that are, in themselves, of no value whatsoever. We delay the realization that our true goal is not to deliver some fragment of intrinsically valuable “content” rumoured to reside, like a mythical unicorn, in the furthest reaches of our product; our true goal is instead to find something, anything to mete out over the course of 5–60 hours that will somehow account for the absence of real instrinsic value. It is not, therefore, the content that truly matters to us; it is the meting out.

Though the products we design ought to provide value for players and money for us, they currently only pretend towards the former function while actually performing solely the latter one. This deception permits us to continue making intrinsically simple products, avoiding transformative changes to our designs that we fear would render them less digestible; we instead rely upon a pattern of amelioration by technical advancement wherein we deliver as few intrinsic features as possible (and the same ones over and over again), but with intricate fashions heaped upon them. We have abandoned game literacy in the process, and as a result we now find ourselves trapped in the business of making increasingly-elaborate pop-up books.

Read more…

Games as Histories

rainbow

The internet has trouble understanding optical phenomena

Why is it that so many of my friends who count Diablo 2 amongst their all-time favourite videogames find themselves so disappointed with its sequel?

It is tempting to point into the horrific maelstrom that is public opinion on the internet and claim that Diablo 3 suffers predominantly from an overabundance of rainbows; now, while I do believe said rainbows represent a tangible detail to which some have pointed in an effort to articulate legitimate concerns with the tone of the game world, that is only one piece of the story. The remainder involves the game’s notorious Auction Houses, which are far more interesting to discuss because they reveal something surprising about loot and its design. Diablo 3 commits the cardinal sin of Game Design Idolatry: It is so fixated on the whirring and buzzing of its item generating machine that it loses sight of the aesthetics for which that system was originally designed, and which made Diablo 2 so memorable.

Read more…

Smacking Some Reason Into Your Akai MAX49

A Photograph of the Akai MAX49 MIDI Controller

I don’t care what the internet says; I think the red paint looks sexy.

I bought an Akai MAX49 MIDI controller recently. It’s an impressive device boasting a nice, stiff keybed, a reasonably-supple set of pads and, of course, its big killer feature: Four banks of eight responsive LED touch faders designed primarily to make your neighbours jealous. A musician, upon unboxing such an instrument, might set about playing music with it; I, however, am no musician.

The first thing I did with my MAX49 was dive into its configuration settings in an effort to set it up just so for use with Propellerhead’s excellent Reason software. Akai offers some presets that work with Reason’s ‘Remote API’, an interesting and mysterious Lua-based scripting system for binding the various physical knobs and dials on any MIDI device to the virtual ones inside Reason. These are pretty good for the most part, but I encountered one major annoyance almost immediately: The controller’s ‘responsive’ faders (which one would expect to work just like the motorized ones on a mixing board) were capable of sending data out to Reason but not of receiving it from Reason. Thus I could use my finger and the MAX49 to move a fader on one of Reason’s virtual line mixers, but if I then used my mouse pointer to tweak that fader in the application the change would not be represented on my physical controller. This was not acceptable.

Read more…

The Strawberry Game Jam

Screenshot of The Wheel

I did a game jam last weekend! You can look at the result right here.

This game is a parable about time and society. A person must journey all the way around the surface of the globe, following the footsteps of his doomed countrymen into hell and confronting the ancient thing that brought them there.

I developed this project alongside Dylan Bremner between the hours of 7:30pm on a Friday night and 4:00pm the following Sunday. We used Flash’s fancy newish Stage3D (via the somewhat-interesting StarlingPunk framework). The rings consist of rectangular textures bent over circle-shaped triangle fans using some clever UV mapping and programmable shaders. I am very happy with it. It was a productive and enlightening experience.

Special thanks to Phil and especially Emily for allowing us to stink up their suite for an entire weekend!

Narrative Economy Makes Walking Dead Work

In drama there is a principle known as “Chekhov’s gun”. It goes like this: If, in act one of a play, you place a loaded gun prominently in the middle of the stage so that it becomes notable to the audience, it behooves you to fire the thing before the curtain falls. If you don’t, it means you’ve wasted the audience’s time and attention on a meaningless detail when these precious resources could instead have been spent on something that contributes more earnestly to the quality of the story. The concept is most frequently applied to storytelling, but in fact it’s applicable to all forms of design and can be restated in a way familiar to all creators: Strive to make every feature of your product as purposeful as it can possibly be. Good design is economical; it maximizes utility while minimizing waste.

Previous videogames aiming to provide the player with interesting narrative choices suffer from a lack of economy, and this is partly why we find game stories to be so inferior to those of film or novels. Consider, for example, the time-honoured trope of wheeling two characters the player has never seen before out onto the stage, explaining some conflict in which they’ve mired themselves, then asking the player to decide everyone’s fate. Often the choice allows the player to make some clearly defined moral stance (the proverbial ‘baby save/puppy kick’); occasionally it involves thought-provoking ethical judgments (‘gray area’). Ideally the player asks herself: What is the best way to handle this situation? Pragmatically, however, I can think of a few more pressing concerns: Who the hell are these people, why should I care about them, why should I care what happens to them, and how does any of this affect me?

Read more…

Violence in Games Has Gotten Weird

One afternoon in university a classmate asked me what I wanted to do after graduating. I immediately said “Video games!”, and she was surprised; she thought I’d go off to make weird Arduino-based projects for the Surrey Art Gallery or something. She didn’t think me the type to play or want to make video games. Eying me suspiciously she asked: “Aren’t those really violent?”

I was expecting this; I was, in fact, prepared for it in the way only an obnoxious know-it-all like myself can be prepared. “Well actually…” I began, eager to waste the next two minutes of her life ranting about my favourite subject. “The medium’s fixation on violent conflict is an unfortunate artifact of early design constraints. Just underneath the blood spatter are interesting spatial and temporal problems that constitute the actual game, and designers dress those things up with violence only because the precedent has become deeply ingrained and difficult to erase.”

Read more…