Running a python/shell script from the UnityEditor

While working on your game, sometimes you develop little python or shell scripts that help along the process, and it’d be nice to run them from the editor.
Or better yet, during your automated build process, have it call out to this from within Unity.

It’s actually quite simple, and you can even capture the output into the editor.

[MenuItem("MyGame/Downscale Reference Textures")]
public static void DownscaleRefTextures() {
        // using System.Diagnostics;
    Process p = new Process();
    p.StartInfo.FileName = "python";
    p.StartInfo.Arguments = "";    
        // Pipe the output to itself - we will catch this later
    p.StartInfo.CreateNoWindow = true;
       // Where the script lives
    p.StartInfo.WorkingDirectory = Application.dataPath+"/SpriteCollections/"; 
    p.StartInfo.UseShellExecute = false;

        // Read the output - this will show is a single entry in the console - you could get  fancy and make it log for each line - but thats not why we're here
    UnityEngine.Debug.Log( p.StandardOutput.ReadToEnd() );

ios-creating-reusable-uiviews-with-storyboard – Part 2

This has is an updated version of ios-creating-reusable-uiviews-with-storyboard for Xcode 6.

TL:DR version:

  1. Create a new UIView subclass name it MyView.h/MyView.h
  2. Create a new XIB name it MyView.xib
  3. In MyView.xib select the File's Owner and set the class (using the right pane, third tab) to MyView
  4. Create an IBOutlet in MyView.h is of the type UIView*, call it contentView
  5. In InterfaceBuilder (with MyView.xib open) right-click drag the File's Owner the root view, and link it to contentView
  6. In MyView.m, override -awakeFromNib with the following:
    -(void)awakeFromNib {
        [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil];
        // The following is to make sure content view, extends out all the way to fill whatever our view size is even as our view's size is changed by autolayout
        [self.contentView setTranslatesAutoresizingMaskIntoConstraints:NO];
        [self addSubview: self.contentView];
        [[self class] addEdgeConstraint:NSLayoutAttributeLeft superview:self subview:self.contentView];
        [[self class] addEdgeConstraint:NSLayoutAttributeRight superview:self subview:self.contentView];
        [[self class] addEdgeConstraint:NSLayoutAttributeTop superview:self subview:self.contentView];
        [[self class] addEdgeConstraint:NSLayoutAttributeBottom superview:self subview:self.contentView];
    +(void)addEdgeConstraint:(NSLayoutAttribute)edge superview:(UIView *)superview subview:(UIView *)subview {
        [superview addConstraint:[NSLayoutConstraint constraintWithItem:subview

So that’s the first part, the second part is to create a UIView in some other XIB or storyboard, do whatever autolayout stuff you want with it and set it’s UIView class to “MyView”. When the XIB is loaded and displayed -it will show your view in there allowing you to customize views and reuse them.

Open two instances of Unity at once

Sometimes you have a project that you’re using as reference, maybe you added some functionality in a previous project or you downloaded a sample project and you are trying to recreate that thing in your new project. It would be great if you could have them both open side by side so you can compare them right?

Unfortunately if you try to open Unity by clicking the icon, it will just bring your current instance into focus, so what can be done?

Here’s a simple trick that allows you to have two instances of Unity open at once, open the second instance from the command line and point it to a project.

$ /Applications/Unity/ -projectPath ~/projects/coolgame

Note: You cannot open the same project twice, so if you have to do that create a temporary copy of the project.

Create iOS / Android icons from master icon

This is just a simple script that will create your iOS icons from a masterfile.
I’m using it on a Unity project (Even though Unity will make the icons for you, the way it resizes the images leaves them appearing jaggy).

It works best with a 1024×768 icon as the source

# Author: Mario Gonzalez
# Modified for iOS7 from:
# App Icon - iPhone iOS7+
sips --resampleWidth 60 "${f}/${1}" --out "${f}/icon60.png"
sips --resampleWidth 120 "${f}/${1}" --out "${f}/icon120.png"
# App Icon - iPhone <= iOS6
sips --resampleWidth 57 "${f}/${1}" --out "${f}/icon57.png"
sips --resampleWidth 114 "${f}/${1}" --out "${f}/icon114.png"
# App Icon - iPad iOS7+
sips --resampleWidth 76 "${f}/${1}" --out "${f}/icon76.png"
sips --resampleWidth 152 "${f}/${1}" --out "${f}/icon152.png"
# App Icon - iPad <= iOS6
sips --resampleWidth 72 "${f}/${1}" --out "${f}/icon72.png"
sips --resampleWidth 144 "${f}/${1}" --out "${f}/icon144.png"
# Spotlight iOS7+
sips --resampleWidth 40 "${f}/${1}" --out "${f}/icon40.png"
sips --resampleWidth 80 "${f}/${1}" --out "${f}/icon80.png"
# Spotlight - Ipad <= iOS6
sips --resampleWidth 50 "${f}/${1}" --out "${f}/icon50.png"
sips --resampleWidth 100 "${f}/${1}" --out "${f}/icon100.png"
# Spotlight - iPhone <= iOS6
sips --resampleWidth 29 "${f}/${1}" --out "${f}/icon29.png"
sips --resampleWidth 58 "${f}/${1}" --out "${f}/icon58.png"
# iTunesArtwork
sips --resampleWidth 512 "${f}/${1}" --out "${f}/iTunesArtwork"
sips --resampleWidth 1024 "${f}/${1}" --out "${f}/iTunesArtwork@2x"

sips --resampleWidth 96 "${f}/${1}" --out "${f}/icon96.png"
sips --resampleWidth 48 "${f}/${1}" --out "${f}/icon48.png"
sips --resampleWidth 36 "${f}/${1}" --out "${f}/icon36.png"

Use it as such:

$ ./  iconmaster.png

Note you made need to run chmod +x on it before it will be recognized as executable

Using Greensock JS / TweenMax in a Dart application

Once you use Greensock / TweenMax / TweenLite, you don’t really want to use anything else.
It’s fast, it’s feature rich, and it works on more browsers than dart itself.
This is a quick post on how to use the animation library, it’s surprisingly easy.

  • First import the dart:js library
    import 'dart:js';

  • Next, add dart.interop.js to your HTML after your own apps script tags.
    Mine looks like this:


Now to call JS from dart you must follow the js-interop syntax, which I agree is a bit annoying – but one approach is to create a wrapper class / function for it.

  • With that out of the way, here is an example of a Tweenmax call to modify the Y / Alpha values of a div:
      // You can also just pass the element's ID instead to greensock
      // but assuming we already retrieved it or may not have an id we would use this method
      HTMLElement divToAnimate = querySelectorAll("#myDiv");
      // Context refers to the JSContext, and retrieves global window objects
      context['TweenMax'].callMethod("to", [divToAnimate 
            new JsObject.jsify({
                  "delay" : 0.5,
                  "y": "40"
                  "autoAlpha": 0

      // A simpler one for reference
      context['TweenMax'].callMethod("to",["#myDiv", 0.15, new JsObject.jsify({x:100})]);

We can think of Context as referring to the Window object in the javascript context. So we retrieve it, and then call a method on it. Passing the method name to and then an array of parameters. For the last parameters, we create a new javascript object using the JsObject.jsify method which takes a map of primitive types with strings as keys.

In the next post / or an update to this one, I will show you how to create a simple wrapper class to make using Greensock more like calling it from JS

Placing an AppKit controls over a NSOpenGLView / CinderView

Currently working on an OSX application that requires UI controls to live above a CinderView (Which is a type of NSOpenGLView).

Obviously first I tried to simply place the objects above one another in InterfaceBuilder, but that had no effect. The NSOpenGLView always draws above all other content.

Next I tried some information someone suggested, with switching to layer-backed views.
That crashed my application on startup.

Instead what I found that worked, was to create a separate NSWindow, and style it to be transparent and place it inside of your NSWindow that contains the CinderView / NSOpenGLView.

Create a window to house your AppKit UI controls, and place your NSView inside

    // Transparent UI window
    CGRect wRect = self.window.frame;
    NSView *contentView = self.window.contentView;
    CGRect cRect = contentView.frame;
    CGRect rect = CGRectMake(wRect.origin.x, wRect.origin.y, cRect.size.width, cRect.size.height);
    self.overlayWindow = [[NSWindow alloc]initWithContentRect:rect
    self.overlayWindow.backgroundColor = [NSColor clearColor];
    [self.overlayWindow setOpaque:NO];
  // Add it to the window which contains our NSOpenGLView
    [self.window addChildWindow:self.overlayWindow ordered:NSWindowAbove];
    // Place UI in overlay window
    self.settingsController = [[SettingsViewController alloc] init];
    [self.overlayWindow.contentView addSubview:self.settingsController.view];

[iOS] Creating reusable UIViews with Storyboard

I’m a big fan of using Storyboards to act as the glue for your application.
It just makes everything much easier, and makes your program feel like a cohesive application instead of a random assortment of UIViewControllers

However one problem is that, Storyboards don’t lend themselves to having reusable views.
Which I find kind of odd, because it seems common that you would have a view that needs to exist in multiple screens for myriad reasons in a lot of applications.

Wellp, it’s actually not that difficult to do – although definitely falls in the ‘tricky’ category.
Continue reading [iOS] Creating reusable UIViews with Storyboard

Compiling LESS from a node.js script

LESS is a tool that allows you to write CSS in a programmer friendly way (with variables, and some simple functions), it then converts it to regular CSS for browser friendly consumption.

It’s amazingly easy to use, during development you don’t have to change a thing.
You simply import your .less file, then under you import ‘less.js’ and it does it’s magic.

Eventually you need to preprocess it as part of your build operation.

For some reason I could not find a simple response for how to do this.
I found many articles / answers for how to run LESS from the command line, or using it with Express to pre-compile it for you when serving then cache it.

Here’s what I ended up using, much of it referenced from the lessc command line tool.

var less = require( 'less' );
var fs = require( 'fs' );
var path = require('path');

// Load the file, convert to string
fs.readFile( '../less/gaf.less', function ( error, data ) {
  var dataString = data.toString();
  var options = {
    paths         : ["../less"],      // .less file search paths
    outputDir     : "../css",   // output directory, note the '/'
    optimization  : 1,                // optimization level, higher is better but more volatile - 1 is a good value
    filename      : "gaf.less",       // root .less file
    compress      : true,             // compress?
    yuicompress   : true              // use YUI compressor?

  // Create a file name such that
  //  if options.filename == gaf.js and options.compress = true
  //    outputfile = gaf.min.css
  options.outputfile = options.filename.split(".less")[0] + (options.compress ? ".min" : "") + ".css";
  // Resolves the relative output.dir to an absolute one and ensure the directory exist
  options.outputDir = path.resolve( process.cwd(), options.outputDir) + "/";
  ensureDirectory( options.outputDir );

  // Create a parser with options, filename is passed even though its loaded
  // to allow less to give us better errors
  var parser = new less.Parser(options);
  parser.parse( dataString, function ( error, cssTree ) {
      if ( error ) {
        less.writeError( error, options );

    // Create the CSS from the cssTree
    var cssString = cssTree.toCSS( {
      compress   : options.compress,
      yuicompress: options.yuicompress
    } );

    // Write output
    fs.writeFileSync( options.outputDir + options.outputfile, cssString, 'utf8' );
    console.log("Converted Less: '" + options.filename + "', to CSS: " + options.outputDir + options.outputfile);

var ensureDirectory = function (filepath) {
  var dir = path.dirname(filepath);
  var existsSync = fs.existsSync || path.existsSync;
  if (!existsSync(dir)) { fs.mkdirSync(dir); }

A Little About Digital Audio and Linear PCM

This is from Apple’s documentation on CoreAudio.

Since I find wikipedia to be only marginally helpful these days (it actually suffers from TOO much information)
I found it explained these concepts so well, I had to quote it for future reference.

A Little About Digital Audio and Linear PCM
Most Core Audio services use and manipulate audio in linear pulse-code-modulated (linear PCM) format, the most common uncompressed digital audio data format. Digital audio recording creates PCM data by measuring an analog (real world) audio signal’s magnitude at regular intervals (the sampling rate) and converting each sample to a numerical value. Standard compact disc (CD) audio uses a sampling rate of 44.1 kHz, with a 16-bit integer describing each sample—constituting the resolution or bit depth.

A sample is single numerical value for a single channel.
A frame is a collection of time-coincident samples. For instance, a stereo sound file has two samples per frame, one for the left channel and one for the right channel.
A packet is a collection of one or more contiguous frames. In linear PCM audio, a packet is always a single frame. In compressed formats, it is typically more. A packet defines the smallest meaningful set of frames for a given audio data format.

In linear PCM audio, a sample value varies linearly with the amplitude of the original signal that it represents. For example, the 16-bit integer samples in standard CD audio allow 65,536 possible values between silence and maximum level. The difference in amplitude from one digital value to the next is always the same.

Excellent open-course, from NAND to Tetris

Came across this while I was reading an entry on #ALTDEVBLOGADAY. The entry was part 2 of 9, C / C++ Low Level Curriculum part 2 which is interesting in it’s own right.

There was a link to this interesting MIT open course called:
From NAND to Tetris, which discussing building an entire computer from first principals. The idea is to work backward, instead of starting at high-level abstraction beginning at the lowest interesting level in computer science (logic gates)

Although not required, it’s meant to be consumed with it’s own accompanying book, which i’ve already ordered and should get here by Tuesday – i’m very excited to start reading it and going through the course.

The Elements of Computing Systems: Building a Modern Computer from First Principles