Data Serialization on iOS with Unity and AOT Problems

Super quick tip!
I’ve come up with a problem when making a generic data serialization method in which I write my data to a binary file, which is an error that only occurs on iOS because it can’t run JIT ( Just-in-time ) compilation and/or AOT ( Ahead-of-time ) compilation because it doesn’t allow runtime code generation.

There are some answers on Unity Ansers, but this forum post had the same problem as I was, and there is a fix that did it for me, that’s on Unity Answers here with a pretty good explanation.

So, yup, my solution was to add that same piece of code on the file where I am invoking the code.

 void Awake( )
    #if UNITY_IOS
        // Forces a different code path in the BinaryFormatter that doesn't rely on run-time code generation (which would break on iOS).
        Environment.SetEnvironmentVariable("MONO_REFLECTION_SERIALIZER", "yes");
        // ...

So just in case, I’ll leave this here for future reference. ;)

Simple UIImage Caching in Swift

This is a snippet of code that will cache images downloaded from an online source, and provide them when needed. I still have some work to do on it, but right now it works pretty fine.

//  ImageCache.swift
//  Created by Michael Adaixo on 16/07/15.

import UIKit

// TODO:
// - Implement LRU Algorithm ( Least-Recently-Used ) to clear unused images from memory
// - Try to make some sort of PriorityQueue out of this..
// - Be awesome. ( Check )

class ImageCache {
    static let sharedInstance = ImageCache()
    private var _cache: [String : UIImage]!
    init()  {
        _cache = [String : UIImage]()
    func find( imageUrl: String ) -> UIImage? {
        if isCached( imageUrl ) {
            let key = stringToBase64( imageUrl )
            return _cache[key!]
        return nil
    func cacheImage( imageUrl: String ) {
        if !isCached(imageUrl) {
            UIImage().loadAsyncFromUrl(imageUrl, complete: { (resultingImage) -> Void in
                if let image = resultingImage {
                    self.addNewImage(imageUrl, image: image)
    func findOrLoadAsync( imageUrl: String, completionHandler: ( image: UIImage! ) -> Void ) {
        if let image = find( imageUrl ) {
            completionHandler( image: image )
            UIImage().loadAsyncFromUrl(imageUrl, complete: { (resultingImage) -> Void in
                if let image = resultingImage {
                    self.addNewImage(imageUrl, image: image)
                    completionHandler( image: image )
    private func addNewImage( imageUrl: String, image: UIImage ) {
        if !isCached( imageUrl ) {
            let key = stringToBase64( imageUrl )
            _cache[key!] = image
    private func isCached( imageUrl: String ) -> Bool {
        if let key = stringToBase64( imageUrl ) {
            if _cache[key] != nil {
                return true
        return false
    private func stringToBase64( string: String ) -> String? {
        let imageData = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
        return imageData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.allZeros)

I’m using a dictionary to keep track of the images, with their Base64 encoded urls as keys.

Example usage goes like:

ImageCache.sharedInstance.findOrLoadAsync(imageUrl, completionHandler: { (image) -> Void in
// do something with image (UIImage)

PS: Also, that UIImage().loadAsync is an UIImage Extension method I have lying around :)

// Will asynchronously download an image from the path(url)
// that you provide, and return you the UIImage on the main queue
func loadAsyncFromUrl( path: String, complete: (resultingImage: UIImage?) -> Void ) {
    // example fetch photo
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true

    let url = NSURL(string: path)
    var request: NSURLRequest = NSURLRequest(URL: url!)

        queue: NSOperationQueue.mainQueue(),
        completionHandler: { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
            if error != nil {
                println("[UIImage.loadAsyncFromURL] Error: \(error)")
                var image = UIImage(data: data)
                complete(resultingImage: image)

Change font weight by code in Swift

let currentFont = label.font
let fontName = currentFont.fontName.componentsSeparatedByString("-").first
let newFont = UIFont(name: "\(fontName!)-Light", size: currentFont.pointSize)
label.font = newFont

This snippet changes the current font of a label to a Light version of it ( in case it exists ). Font names are ( in this case, it was ‘.HelveticaNeue-Regular’ ) appended with their weight. So I get the font name, split it by ‘-‘, and take the first part of the split, ending with ‘.HelveticaNeue’. Now I just create a new font with the light appended to it, with the same size.

Lastly, I switch the font, and there you go.

SuperStems is out for iOS

SuperStems is finally released on the AppStore for iOS! After 14 long days waiting for approval, it finally passed and it up for grabs for free! There are already over 400 downloads and counting, and players are rocking the leaderboard!

I’ve setup a new website for SkyBelow, my new gaming studio.

Edit: I’ve been updating SuperStems since Unity5 was released, and all I can say is that it runs smoother and better looking with the new IL2CPP – converts C# to Cpp to increase performance -, which is awesome! So far I’m testing it on my device, but you should get the update in a couple of weeks. Just enough time to send the new build and get it approved again by Apple.

Super Stems Post Mortem


B4L4pozCYAAHAwj Super Stems, originally called Stems, started on a gamejam weekend, Ludum Dare 31. The theme was “Entire Game on One Screen”, which many people complained about, me included, since a lot of people were expecting the snowman theme to be chosen. Aside from that, once the theme was announced, I started to make Stems.

So what is Super Stems? Super Stems is a board domination strategy game. You have tiles and board slots. Each tile has three sides, a number attached, and adjacent sides on the board will battle. Upon battle, the higher number will win, and the losing tile will be captured. This is a simple concept that I stripped down from another game I’m planning, which has this basic gameplay with more gameplay mechanics, inventory and multiplayer in it. B4M3HkVCAAAjR2a But since I had only 48 hours to make it happen, I stripped it down to this. A few hours in, I had the tiles and placeholder models and ready to be used in Unity.

I don’t usually take much time in planning during gamejams, I usually go all in with a minimum planning and knowing what I must do and sort and solve problems as they arrive. But since Indies vs Pew Die Pie gamejam went really bad because from the lack of planning, this time around, I took some time to plan ahead and think of what I wanted to make.


So with my plan written down and my idea right fixed in my head, I started developing the game until I had basic gameplay done. If you asked me by then, how much more time would I take me to finish a minimum viable product, I would’ve said a week, maybe less, but oh boy was I wrong. First things first, the gamejam atitude of coding this and that without taking much care, because time is of the essence, is bad. I don’t use magic numbers, nor hardcode anything. I usually take care in writing beautiful and maintainable code. So for that end, I was good. On the other hand, I manually placed the grid and linked neighbors, one by one. Since the original grid had only 9 pieces, it was fast and did the job. Finding after a few days that some of those links were broken/switched, was bad tho.. Mistake #1.


But nonetheless, everything was in place, I had the grid, the basic Turn-by-Turn gameplay, basic animation, tile capturing, teams, score. I was just missing an opponent.. better yet.. an Intelligent Opponent. Making the Artificial Intelligence was hard. It was hard because of mistake n# 1, not having a generic grid, in which I could make the calculations required to make it easier for me. Having a properly made grid system, I could have made methods to make my life so much easier, but nooo.. I might have written the battle, capture, AI play code at least 5 times! And by this I mean, really starting from scratch. Taking pen and paper, putting it all in a new perspective. And every time I did it, something good came out of it. Every time it god better. Obviously by now, the 48h period had long gone. I was more like two weeks after the deadline, mainly because I was working on it part time, after work, 3 or 4 hours a day, and you can only do so much.


But still after those AI changes, it wasn’t working properly yet. I wanted to make it smarter. After another brainstorming session with pen and paper, I finally tweaked the algorithm to make it the way I wanted to. You can now have decent battles with it. It will lose, but also win. So far, from online gameplay and local testing, my analytics say that the AI wins above 60% of the times, so I’m ok with that. During that time, while I was trying to get the AI right, I kept changing the UI, textures and models. The images speak for themselves.


Right now the game is ready to be published. Its maybe not as polished as I would like it to be, but I have to release it, get feedback, and then I’ll see what I’ll do with it. I’m already thinking of other games I want to make. This is my second ‘board’ game. This one has a new gameplay type, which is good, since I always try to make new gameplay on each game. So I’ll be releasing the game in the upcoming weeks, hopefully this will get some players. At least more than my previous one.

Memtiles Development Status

We are on the final stretch!

The last art assets are being made. The 3D models are being updated and polished. The sound is being adjusted, and the game is being play tested on many different devices by many different people to make sure everything works fine when launching.

So right now is the most crucial part, the last tiny bits of detail that need to be polished. By the end of the week, the game will be in its final form, ready to launch. But first, I’m going to have to make some promotional stuff, like videos, image headers and icons, set up a website, and write a “press release” to send to blogs for possible reviews in order to advertise the game.

It’s been a long ride and hopefully all continues well as I have more games in mind to make :)

The game is going to be released for Android devices first, then maybe iOS and WP8, for both mobile phones and tablets. Maybe later on I’ll release a web build but for now, this is the plan.

Cheers :)

Memtiles is almost done

After nearly a month after the beta release of Memtiles, I’m nearly in the end of development. I’ve basically being updating and creating new assets, textures, checking for sound effects, hiring for music composition and graphics. So it has been pretty busy. Mainly because I’m working part-time on this project, only when I come home from work, and on weekends.

Today I lost all connections to my assets, prefabs, textures, everything.. I don’t know what happened to Unity3D, but that sure as hell cost me 3 hours rebuilding all prefabs. I guess I should back my things before opening a new branch.. or check what to ignore on bitbucket.. Anyway, I have my prefabs back.

Screen Shot 2013-09-21 at 1.35.38 AM

So now I can actually focus on progressing in the development. I still have game art and sound/music coming up.

Hopefully I will still release this by mid/end october.