Some Utility Code

Every now and then, I’d like to share some of my small utility classes that I’ve made a long time ago but are still being used until now. The following are what I call some of my mini utilities. They can be used in your own Unity projects.

(Note that I’ve removed method description comments so that the code part looks more compact.)

Comment Component

A lot of times have come up where I have an object or prefab that contains a lot of components. Sometimes, I want to be able to note about the values I’ve entered for some component or state why the component is there. Sadly, Unity doesn’t have a feature where you can comment on components (let me know if you know one). However, it’s quite easy enough to roll your own “comment” component.

public class Comment : MonoBehaviour {

    [SerializeField]
    private string text;

    void Awake() {
        DestroyImmediate(this); // auto destroy to save memory
    }

    public string Text {
        get {
	    return text;
	}

        set {
	    this.text = value;
        }
    }

}

// This is the editor script. Place it under an Editor folder.
[CustomEditor(typeof(Comment))]
public class CommentEditor : Editor {

    private Comment targetComponent;

    void OnEnable() {
        this.targetComponent = (Comment)this.target;
    }

    public override void OnInspectorGUI() {
        if(targetComponent.Text == null) {
            // use an empty string so that it won't throw null pointer exception
            targetComponent.Text = "";
        }

        targetComponent.Text = GUILayout.TextArea(targetComponent.Text, GUILayout.Height(100), GUILayout.MinWidth(200));
    }

}

To use, just add the Comment component and type your comment text in the textbox.

CommentComponent

UI Image Sprite Animation

I tried to use the animation timeline for animating sprites in a UI Image. But it didn’t work or maybe I was using it wrong. I got impatient, so I turned to code.

public class ImageAnimation : MonoBehaviour {

    [SerializeField]
    private Image image;

    [SerializeField]
    private float framesPerSecond = 15;

    [SerializeField]
    private Sprite[] sprites; // The sequence of sprites comprising the animation

    private float polledTime;

    private int currentFrameIndex;

    private void Awake() {
        Assertion.AssertNotNull(this.image);
        Assertion.Assert(this.framesPerSecond > 0);

        this.polledTime = 0;

        // Reset
        this.currentFrameIndex = 0;
        SetSprite(this.currentFrameIndex);
    }

    private void Update() {
        this.polledTime += UnityEngine.Time.deltaTime;

        // We didn't cache this so we can see the effect of framesPerSecond on the fly like tweaking it in editor
        float timePerFrame = 1.0f / this.framesPerSecond;

        while(this.polledTime > timePerFrame) {
            this.polledTime -= timePerFrame;

            // Show next frame
            this.currentFrameIndex = (this.currentFrameIndex + 1) % this.sprites.Length;
            SetSprite(this.currentFrameIndex);
        }
    }

    private void SetSprite(int index) {
        this.image.sprite = this.sprites[index];
    }

}

This is very straightforward to use. Just specify an Image target, a frame rate, and the sequence of sprites to show. That’s it. It will play on loop. Nothing fancy. I’ve use this on the game over screen of Academia.

GameOver

SelectionSequence

Political Animals had a common UI where you select an item from a finite set of items using next and previous buttons. I’ve noticed that I’m repeating the same code spread across different UI screens. So I made a generic class for this.

public class SelectionSequence<T> {

    private readonly List<T> items = new List<T>();

    private int currentIndex = 0;

    public SelectionSequence(T[] array) {
        this.items.AddRange(array);
        Reset();
    }

    public void Reset() {
        this.currentIndex = 0;
    }

    public void MoveToNext() {
        this.currentIndex = (currentIndex + 1) % this.items.Count;
    }

    public void MoveToPrevious() {
        int decremented = this.currentIndex - 1;
        this.currentIndex = decremented < 0 ? this.items.Count - 1 : decremented;
    }

    public T Current {
        get {
            return this.items[this.currentIndex];
        }
    }

    public void Select(int index) {
        this.currentIndex = index;
    }

    public void Select(T item) {
        for(int i = 0; i < this.items.Count; ++i) {
            if(this.items[i].Equals(item)) {
                Select(i);
                return;
            }
        }

        throw new Exception("Can't find the item to select: " + item.ToString());
    }

    public int Count {
        get {
            return this.items.Count;
        }
    }

    public T GetAt(int index) {
        return this.items[index];
    }

}

// Usage
// Say you have an array of LanguageOption
LanguageOption[] languages = ...;
SelectionSequence<LanguageOption> langSequence = new SelectionSequence<LanguageOption>(languages);

// When next button is clicked
langSequence.MoveToNext();

// When previous button is clicked
langSequence.MoveToPrevious();

// Do something with current selection
ChangeLanguage(langSequence.Current);

This kind of selection have come up in Academia, too.

SelectionExample

These are just some of my cute little classes. They’re small but they have been very useful. Here’s some programming tip, think of making classes like making a new invention or a device. That way, you will think in terms of narrowing functionality as much as possible and expose only appropriate public methods. This will also make your classes more modular. Over time, you will develop a library of robust and reusable code.

Advertisements

My Random Tips to Manila Game Jam

I’ve joined the last 4 game jams. I’ve joined since the first one. I guess I can consider myself a war veteran. The random tips that I’ll give out to you in this post are all based on experience. It’s random because I don’t have time to organize my thoughts. The game jam starts tomorrow! I’ll just write away whatever I can think of. Note also that I’m a programmer, so I’m probably addressing more programmer stuff here.

My first jam
My first jam

Things to bring

I have a list of things to bring for a game jam since the second one. I also updated it for each new stuff brought on the succeeding jam. Note that I stay at the venue for the entire duration of the jam. Here’s my list:

  • Laptop
  • Laptop Battery
  • Laptop Cord
  • Mouse – I see people use the track pad while working. While they are hardcore, I also find it inefficient. So use a mouse or tablet.
  • Cellphone
  • Cellphone Charger
  • Facewash
  • Slippers
  • Towel
  • Liquid Soap – because solid soap is messy
  • External Drive
  • Money
  • Headphones – Do not disturb others while integrating music and sound effects
  • Jacket – Very important because it’s January, it’s cold, plus the AC in a confined space
  • Umbrella – Yeah, I’m a boy scout. Just in case it rains when going home.
  • Nail Cutter – For cutting annoying stuff on my finger like a protruding extra tissue that keeps in the way while typing
  • Snacks – Organizers are very kind for providing snacks. But there are cases when I wanted to munch something and there’s no other food. Last year, I brought Boy Bawang which I happily share with other jammers.
  • Pillow – Please bring pillow. You just can’t borrow other people’s pillow. You’re saliva might mix with mine or your face might land on that part where the saliva has dried.
  • Sleeping Bag – During the first jam, this was the prized commodity. Everybody was waiting in line for that one sleeping bag. Poor owner.
  • Ballpen
  • Notebook
  • Coffee – There would be lots during the event but they might not be your cup of tea. So bring your kind of tea.
  • Mug – Saves a lot of styro cups. You know, environment thingy. Just do those little things that really helps.
  • Home Keys
  • Perfume or Cologne – Just to hide that you didn’t take a bath yet. Bambini works like a charm.
  • Deodorant – If you do get shower at the venue
  • Toothbrush and toothpaste – Please, please, please
  • Petroleum Jelly – I have chappy lips and it’s cold, this one’s very helpful for me
  • 2 Comfy Shirts – The ones you wear in your house while chillin
  • 1 Comfy Pants/Shorts
  • 1 Dressed to Kill Outfit – For the awarding and media
  • Underwears – Of course
  • e-Ticket (Eventbrite) – This is new on my list. Never forget because this is your pass to free food.

What happens in a jam

The structure of Manila Game Jam hasn’t changed much for the past 4 years. These are the major activities that happens in sequence:

  • Theme revelation
  • Game idea pitching
  • Form/Join a team
  • Work, work, work
  • Submit/Upload game to Global Game Jam site
  • Game showcase and recognition ceremonies

Why did you join?

I have one primary reason and secondary reasons why I join jams. The primary one is “I want to have a new game under my belt”. The secondary ones could be anything like try out my new AI skills, meet crush, work with a stranger, build an MMO, etc… I do hope that everybody has the same primary reason as I do.

What kind of game? What team?

There will be lots of game ideas at the jam. Everybody just loves to pitch games during pitching time. But do think wisely about the games that you would like to work on and the team that you will be working with. Here are my criteria:

  • Can it be done within 24 hours? – But the game jam is for 48 hours? Wrong! I’ll expound on this later but do trust me that you only have roughly 24 hours to work on your game. That’s 3 man days in one go. If you’re a professional, determine if the game can be completed in 3 office days.
  • Does the team have the skills to make that game? – Some game ideas are so profound. When I hear a game idea, what comes to my head is, how do I implement that? Have I done that before? Can I do it? Is it possible? Does anybody from the team know how to do that? You can lose that 24 hours very quickly if the team doesn’t know how to do something.
  • Can I work with these people? – This is a very important question. You have to know yourself and how you deal with others. Remember that you will be stuck with them for the weekend.

How to develop the game?

I always start with something I call the minimum playable game. Most game ideas in jams tend to be simplistic. When it comes down to making it, I suggest you strip it down more until there’s nothing more to take. Let’s take the game Mario for example. How do you make an MPG out of that? What are the bare elements?

  • Starting point
  • Flat ground
  • A character that can move forward
  • End point (win condition)

If you have these, you basically have a complete game that you can submit. The point of MPG is to have a solid ground such that you can start your incremental iteration. It’s like you’re building the skeleton first, then add the muscles, tissues and other details. You can add other features little by little, test them, and remove them if it feels wrong. You repeat this cycle as long as you have time. The main benefit of this is that you always have a working game for each feature you add. The game works even if you failed to add the other features that you planned. By completing the MPG first, you maximize your time.

To continue the Mario example, I would probably implement jump next. Then add some blocks. Then some death pits would be nice. If there’s still time, how about a chicken enemy.

This brings me back to the first game jam with our game Crease. The game is about folding platforms to get the plug to the socket. The initial concept was not just about folding. There were a lot of crazy features that my designers have come up. What we were able to complete, however, was only the MPG of that game. We still won Jury’s Prize and Participant’s Choice. MPGs are not bad.

Crease
Crease

Ugly is beautiful

Don’t wait for your artist to finish his/her art. You can tell your artist to work on an asset but you should continue making the other stuff using whatever ugly placeholder art you can use. Box and circles are very handy. You can easily integrate the actual asset once it’s done.

You have a beautiful code…

… says no jammer ever! Stop looking for the most elegant code. Use the easiest and fastest that you know that does the job. Use brute force whenever you can. Nobody cares about your super efficient occlusion culling algorithm. Players don’t look at your code when they play your game. Remember that in game jams, the value of a game is measured by its game play, not code.

Bring them down to the ground

As a programmer of a team, you should be an asshole to your game designers and artists. Game designers are crazy by default. They should be. You’re the one who will bring them back to reality from their dreams.

Artists could be pain in the ass as well. They could make a 2048×2048 texture or a 30-frame sprite animation of a 256×256 character. Bring their senses back.

Be prepared to say things like “No”, “Wtf is that”, “We don’t have time”, “I don’t want to implement that”, “You’re crazy”, “It’s impossible”, “We should make another game”. You have to be firm. Remember, you only really have 24 hours.

My 2011 game
My 2011 game

Sleep

We always hear that macho banter “I’m not gonna sleep. I’m used to that. Bring it on!” That guy will most probably make a buggy game, would have a headache, easily irritated, probably emotional, and will not report for work or school on Monday. Are you a macho programmer now? No, seriously, make time for sleep. Like regular sleep, at least 6 hours. Not only it will refresh you, it will increase your productivity, and saves you time. It prepares you for the next day so that you stay awake and work longer. Trust me on this.

Take a bath you pig

This is like sleep. It freshens you up and takes away that eeeky dirty feeling. Not only that, it serves as a reset. It removes you for a while from your monitor so you can empty that full mind.

Eat, never be hungry

Stop working and line up for food as soon as it is announced that it is ready. Eat leisurely. Enjoy this mandatory break. Get back to work as soon as you’re done. You don’t want cold food and you certainly don’t want to be a hungry programmer. It takes more effort to code when you’re hungry.

You only have 24 hours

Well, roughly. Think about the following that takes time:

  • ~12 hrs – Sleep for two nights
  • ~3 hrs – All meals
  • ~1 hr – Shower time for two days
  • ~2 hrs – Occasional breaks, stretch, small talk

That’s already 18 hours. Also note that development does not start right away. There’s keynote speech, theme revelation, game idea pitching, forming a team, yadda, yadda, yadda. These take time. Some would probably want to go home (hello travel time). What does that leave you?

48 hours is an illusion. You should keep your state of mind that you only have 24 hours development time. Keep this into consideration when selecting the game to implement, and the features to add.

See ya there!

I still have lots of thoughts and tips but this post is getting long. Maybe a part 2 for next year. I hope you learned a lot. Don’t forget to have fun. Good luck, and see you at Globe Labs!