The idea of this post is to show different ideas and analysis on how to use Unity UI Text to show numbers without garbage generation. I need this for a framerate counter and other debug values.

Test case

Shows a fixed digit length number in screen, regenerated each frame with a new random value.

alt text Shows how the test scene used for all test cases work.

Using Strings

Since strings are immutable in c#, common operations on strings generates new strings and hence allocates new heap memory. If you are using strings as temporary values like showing a changing number in a UI text then that memory becomes garbage. In PC that garbage could go unnoticed but not in mobile devices since that could derive in a hiccup when the garbage collector decides to collect it.

The idea with these tests is to try to use make the label work with strings without garbage generation. To detect generated garbage I am using the Unity profiler and avoiding ToString() of int, float, etc, to just calculate the cost of the string manipulation for now.

String concatenation

String concatenation generates 30 Bytes per frame since internally String.Concat() calls String.InternallyAllocateStr().

It is not as bad as expected, it is just creating a new string with the length of the first string plus the second and then it copies their values. Obviously it becomes worse when multiple concatenations are done in secuence.

Test code:

Text text;
 
static readonly string[] numbers = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
 
void Start () {
    text = GetComponent<Text> ();
}
 
void Update () {
     
    string a = numbers[UnityEngine.Random.Range(0, numbers.Length)];
    string b = numbers[UnityEngine.Random.Range(0, numbers.Length)];
 
    text.text = a + b;
}

String format

Using string.Format() generates 176 Bytes per frame, internally is using String.FormatHelper + StringBuilder.ToString().  The first one creates a new StringBuilder and the second is the transform from StringBuilder to string.

Test code:

 Text text;
 
 static readonly string[] numbers = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
 
 void Start () {
     text = GetComponent<Text> ();
 }
 
 void Update () {
     string a = numbers[UnityEngine.Random.Range(0, numbers.Length)];
     string b = numbers[UnityEngine.Random.Range(0, numbers.Length)];
 
     text.text = string.Format ("{0}{1}", a, b);        
     
 }

String Builder Format

Using cached StringBuilder improves the previous one a bit, it generates 86 Bytes per frame, the AppendFormat is generating garbage and then the set_Length() (used to clear the StringBuilder).

Test code:

 Text text;
 StringBuilder stringBuilder = new StringBuilder(20, 20);
 
 static readonly string[] numbers = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
 
 void Start () {
     text = GetComponent<Text> ();
     stringBuilder.Length = 3;
 }
 -j
 void Update () {
     string a = numbers[UnityEngine.Random.Range(0, numbers.Length)];
     string b = numbers[UnityEngine.Random.Range(0, numbers.Length)];
 
     stringBuilder.Length = 0;
     stringBuilder.AppendFormat ("{0}{1}", a, b);
 
     text.text = stringBuilder.ToString();
 }

Note: If I change the StringBuilder starting capacity and max capacity, the cost is the same but goes to ToString() method instead, but internally to the same method String.InternallyAllocateStr().

String Builder only Append

Instead of using StringBuilder.AppendFormat, change to use only String.Append. This reduces the cost to only 30 Bytes per frame (the same of the first one), the only cost here is the set_Length() which internally calls String.InternallyAllocateStr().

Test code:

 Text text;
 StringBuilder stringBuilder = new StringBuilder(20, 20);
 
 static readonly string[] numbers = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
 
 void Start () {
     text = GetComponent<Text> ();
     stringBuilder.Length = 3;
 }
 
 void Update () {
     string a = numbers[UnityEngine.Random.Range(0, numbers.Length)];
     string b = numbers[UnityEngine.Random.Range(0, numbers.Length)];
 
     stringBuilder.Length = 0;
     stringBuilder.Append (a);
     stringBuilder.Append (b);
 
     text.text = stringBuilder.ToString();
 }

Note: Does the same behaviour if I change starting and max capacity, the cost is the same but is on ToString() instead of set_Length().

String Builder by replacing chars

If instead of Append I replace chars directly by using [] and avoid the set_Length(), the cost is the same, 30 Bytes per frame, since the String.InternallyAllocateStr() goes to set_Chars().

Test code:

 Text text;
 StringBuilder stringBuilder = new StringBuilder(20, 20);
 
 static readonly char[] numbers = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
 
 void Start () {
     text = GetComponent<Text> ();
     stringBuilder.Length = 3;
 }

 void Update () {
     char a = numbers[UnityEngine.Random.Range(0, numbers.Length)];
     char b = numbers[UnityEngine.Random.Range(0, numbers.Length)];
 
     stringBuilder [0] = a;
     stringBuilder [1] = b;
 
     text.text = stringBuilder.ToString();
 }

Note: Again, does the same behaviour if I change starting and max capacity, instead of set_Chars(), the cost is in ToString() method.

String Builder, access internal string by reflection

There is a suggestion at in this post to access by refleciton to _str field from StringBuilder class to avoid the cost of ToString() method.

Test code:

 Text text;
 StringBuilder stringBuilder = new StringBuilder(20, 20);

 static System.Reflection.FieldInfo _sb_str_info = 
        typeof(StringBuilder).GetField("_str", 
        System.Reflection.BindingFlags.NonPublic | 
        System.Reflection.BindingFlags.Instance);
 
 static readonly char[] numbers = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
 
 void Start () {
     stringBuilder.Length = 3;
 
     text = GetComponent<Text> ();
 }
 
 void Update () {
     stringBuilder[0] = numbers[UnityEngine.Random.Range(0, numbers.Length)];
     stringBuilder[1] = numbers[UnityEngine.Random.Range(0, numbers.Length)];
     stringBuilder[2] = (char) 0;
 
     var internalValue = _sb_str_info.GetValue (stringBuilder) as string;
     text.text = internalValue;
 }

In this case, there is no garbage at all. However, I see no change in the UI Text even though the editor shows the text field value is changing, like it is not being redrawn in screen. I suppose that could be because the string pointer is not changing and by taking a look at the Text code from the Unity UI it is comparing with != instead of Equals… not sure here.

 public virtual string text
 {
     get
     {
         return m_Text;
     }
     set
     {
         if (String.IsNullOrEmpty(value))
         {
             if (String.IsNullOrEmpty(m_Text))
                 return;
             m_Text = "";
             SetVerticesDirty();
         }
         else if (m_Text != value)
         {
             m_Text = value;
             SetVerticesDirty();
             SetLayoutDirty();
         }
     }
 }

I tried by forcing layout and vertices dirty after updating internal string, just in case, but had no luck (sad face).

Caching strings

Another option suggested in this blog post is to precache strings for different numbers but that is only reasonable for a small amount of digits. I like it because it is simple and could be generated at runtime, and works well for debug numbers like FPS where the number is normally between 0 and 60.

I tried it and it works really well and generates 0 Bytes per frame.

Test code:

 Text text;
 
 string[] generated;
 
 // Use this for initialization
 void Start () {
     text = GetComponent<Text> ();
 
     generated = new string[100];
 
     // should go from 0 to 99.
     for (int i = 0; i < 100; i++) {
         generated [i] = string.Format ("{0:00}", i);
     }
 }
 
 // Update is called once per frame
 void Update () {
     int random = UnityEngine.Random.Range (0, generated.Length);
     text.text = generated [random];
 }

Rendering numbers directly

One possible way to avoid all this garbage (I mean both the code and the unused memory) is to not use strings at all but to just render to the screen images for each number digit, where each digit is a different sprite.

When making TinyWarriors prototype I did a basic number rendering where I could specify the number of digits and it just created multiple Unity UI Images inside a horizontal layout.

alt text Shows a test using images for each digit instead of a text.

Test code:

public Image[] numbers;

// in order, like 0, 1, 2, ..., 9
public Sprite[] numberSprites;

public bool fillZero = true;

void Start()
{
  SetNumber (0);
}

public void SetNumber(int number)
{
  int tens = (number % 100) / 10;
  int ones = (number % 10);

  var tensActive = fillZero || tens != 0;
  var onesActive = fillZero || number > 0;

  numbers [0].gameObject.SetActive (tensActive);
  numbers [1].gameObject.SetActive (onesActive);

  if (tensActive)
      numbers [0].sprite = numberSprites [tens];

  if (onesActive)
      numbers [1].sprite = numberSprites [ones];
}

public void Update()
{
  int random = UnityEngine.Random.Range (0, 100);
  SetNumber (random);
}

The code could be adapted to support more digits. When profiling it in editor there is a lot of garbage generation, around 1KB per frame, in Canvas.SendWillRendereCanvases() because it is forcing a material rebuild each time a sprite is changed. However, I tested it on devices and it doesn’t so it must be something related with the Unity editor.

Other strategies

Other strategies include minimizing the garbage generation by reducing the text update frequency, for example, by avoiding updating the text if the number didn’t change and/or updating the text from time to time and not every frame.

Conclusion

Since I just wanted a solution for a framerate counter (and other debug numbers) the last solutions are perfect and I believe those could even be extrapolated for other game needs, like showing the player points in an arcade game, with a bit of extra thinking.

References

Here is a list of some articles, forum and blog posts I took a look during the tests and the post writing.

Unity memory optimizations article - https://unity3d.com/es/learn/tutorials/temas/performance-optimization/optimizing-garbage-collection-unity-games

Memory management reference - http://www.memorymanagement.org/

FPS implementation caching strings - http://catlikecoding.com/unity/tutorials/frames-per-second/

Using reflection to set StringBuilder string to avoid garbage - http://www.defectivestudios.com/devblog/garbage-free-string-unity/

FPS Asset - http://blog.codestage.ru/unity-plugins/fps/

Another FPS Asset - https://www.assetstore.unity3d.com/en/#!/content/6513

StringBuilder API - https://msdn.microsoft.com/en-us/library/system.text.stringbuilder(v=vs.110).aspx

Performance tips for Unity for mobile - https://divillysausages.com/2016/01/21/performance-tips-for-unity-2d-mobile/

Unity UI Source code - https://bitbucket.org/Unity-Technologies/ui

Untiy Community Library - https://github.com/UnityCommunity/UnityLibrary


This is a small blog post about a Unity editor window we made at work to simplify our lives when using Unity.

In Unity, when you select a reference to an asset, it is focused in the Project window, losing the current selection and probably the folder you were working on. Since there is no navigation history, most of the time having to search the previous selection is a pain in the ass.

As we were doing some stuff today at work, we were inspired (after two million times we lost our selection) so I decided to do a simple Editor Window to store and show a history of selected objects. It took me like 30 minutes to make it (plus one more hour at home).

Here are the results:

In case you are interested in using and/or improving it, here is the github project:

https://github.com/acoppes/unity-history-window

As always, hope you like it.

Guardar

Guardar


After five years of Global Game Jam vacations, we joined this year’s the last weekend.

It was a really enjoyable time and we had a lot of fun. In this blog post I would love to share my experience as some kind of postmortem article with animated gifs, because you know, animated gifs rules.

The Theme of this jam was “Waves” and together with my team we did a 1v1 fighting game where players have to attack each other by sending waves through the floor tiles to hit the adversary.

Here is a video of our creation:

My team was composed by:

Here are links to download the game and to its source code:

Postmortem

Developing a game in two days is a crazy experience and so much can happen, it is a incredible survival test where you try not to kill each other (joking) while making the best game ever (which doesn’t happen, of course). Here is my point of view of what went right and what could have been better.

What went right

From the beginning we knew we wanted to complete the jam with something done, and with that we mean nothing incomplete goes inside the game. That helped us to keep a small and achievable scope for the time we had.

When brainstorming the game we had luck in some way and reached a solid idea twenty minutes before sharing a pitch to the rest of the jammers, after being discussing by a couple of hours. The good part was not only we were happy with it but it also was related with the theme (we wanted to do a beat’em up but we couldn’t figure out how to link it with it).

Deciding to use familiar tools like Github, Unity and Adobe Animate and doing something we all had experience in some way helped us a lot to avoid unnecessary complications. I have to mention too that half of the team works together at Ironhide so we know each other well.

Our first prototypes, both visual and mechanical, were completed soon enough to validate we were right about the game and they also were a great guide during development. Here are two gifs about each one.

alt text Visual prototype made in Adobe Animate.

alt text Game mechanics prototype made in Unity

Our artists did a great job with the visual style direction which was really aligned with the setting and background story we thought while brainstorming. If you are interested here is the story behind the game.

alt text The awesome visual style of the game.

Using the physics engine sometimes seems like exaggerating a bit, mainly with small games but the truth is, when used right, it could help to achieve unexpected mechanics that add value to the game while simplifying things. In our case we used to detect not only when a wave hits a player but also to detect when to animate the tiles and it was not only a good decision but also really fun.

alt text Animated tiles with hitbox using physics.

Using good practices like prototyping small stuff in separated Unity scenes, like we did with the tile animations, allowed us to quickly iterate a lot on how things should behave so they become solid before integrating with the rest of the game.

Knowing when to say no to new stuff, to keep focus on small, achievable things, even though, from time to time, we spent some time to think new and crazy ideas.

Having fun was a key pillar to develop the game in time while keeping the good mood during the jam.

What could have been better

We left the sound effects to the end and couldn’t iterate enough so we aren’t so happy with the results. However, it was our fault, the dude that did the sounds was great and helped us because a lot (if you are reading, Thank you!). In the future, a better approach would be to quickly test with sounds like voice made or similar downloaded effects from other games, to give him better references to work with.

Not giving room to learn and integrate things like visual effects and particles which would have improved the game experience a lot. Next time we should spend some time to research what we wanted to do and how it could be done before discarding it, I am sure some lighting effects could have improved a lot the visual experience.

We weren’t fast enough to adapt part of the art we were doing to what the game mechanics were leading us, that translates to doing art we couldn’t implement or it is not appreciated enough because it doesn’t happen a lot during the game. If we reacted faster to that we could have dedicated more time in other things we wanted to do.

Too many programmers for a small game didn’t help us when dividing tasks in order to do more in less time. In some way this forced us to work together in one machine and it wasn’t bad at all. It is not easy to know how many programmers we needed before making the team nor adapting the game to the number of programmers. In the end I felt it was better to keep a small scope instead of trying to do more because a programmer is idle. In our case our third programmer helped with game design, testing and interacting with the sounds guy.

Since the art precedes the code, it should be completed with time before integrating it and since we couldn’t anticipate the assets we almost can’t put them in the game. In fact we couldn’t integrate some. The lesson is, test the pipeline and know art deadline is like two hours before the game jam’s end in order to give time to programmers.

Using Google Drive not in the best way complicated things when sharing assets from artists to developers to integrate in the game since we had to upload and download manually. A better option would have been using Dropbox since it automatically syncs. Another would have been forcing artists to integrate them in the game themselves using Unity and Git to share it, but I didn’t want them to hate me so quick so they avoided this growth opportunity.

The game wasn’t easy to balance since it needed 2 players in order to test and improve it. Our game designer tried the game each time a new player came to see what we were doing but that were isolated cases. I believe were affected a bit by the target resolution of the first visual prototype in terms of game space which left us only with the wave speed factor but if we changed to too slow the experience was affected.

We didn’t start brainstorming fast enough, it was a bit risky and we almost didn’t find a game in time. For the next time, we should start as soon as possible.

Some of the ideas we say no because of the scope were really fun and in some way we may have lose some opportunities there.

Drinking too much beer on Saturday could have reduced our capacity but since we can’t prove it we will not stop drinking beer during Global Game Jams.

Conclusion

Participating on the Global Game Jam was great but you have to have free weekends to do it, for some of us it is not that simple to make time to join the event but I’m really sure it worth it.

I hope to have time for the next one and see our potential unleashed again. Until then, thanks my team for making a good game with me in only one weekend.

Cheers.


I’m not inventing anything new here, I just want to share how making mockups and prototypes helped me to clarify and minimize some problems and in some cases even solve them with almost no cost.

For prototypes and mockups I’m using the Superpower Assets Pack of Sparklin Labs which provided me a great way of start visualizing a possible game. Thank you for that guys.

I will start talking about how I used visual mockups to quickly iterate multiple times over the layout of the user interface of my game to remove or reduce a lot of unknowns and possible problems.

After that, I will talk about making quick small prototypes to validate ideas. One of them is about performing player actions with a small delay (to simulate networking latency) and the other one is about how to solve each player having different views of the same game world.

UI mockups

For the game I’m making the player’s actions were basically clear but I didn’t know exactly how the UI was going to be and considering I have small experience making UIs, having a good UI solution is a big challenge.

In the current game prototype iteration, the players only have four actions, build unit, build barracks, build houses and send all units to attack the other player. At the same time, to perform those actions, they need to know how much money they have, available unit slots and how much each action cost.

To start solving this problem, I quickly iterate through several mockups, made directly in a Unity scene and using a game scene as background to test each possible UI problem case. For each iteration I compiled it to the phone and “test it” by early detecting problems like “the buttons are too small” or “can’t see the money because I am covering it with my fingers”, etc.

Why did I use Unity while I can do it with any image editing application and just upload the image to the phone? Well, that’s is a good question, one of the answers is because I am more used to do all these stuff in Unity and I already have the template scenes. The other answer is because I was testing, at the same time, if the Unity UI solution supported what I was looking for and I could even start testing interaction feedback, like how the button will react when touched, if the money will turn to red when not having anymore, etc, something I could not test with only images.

The following gallery shows screenshots of different iterations where I tested button positions, sizes, information and support for possible future player actions. I will not go in detail here because I don’t remember exactly the order nor the test but you could get an idea by looking at the images.

background used for all the tests

ui with different game world scale.

testing with possible future ideas for the game like special actions with cooldown

ui with previous game world scale

buttons in the middle to be near between them

buttons in one side of the screen, wasnt good for right handed

the final result for now

It took me like less than 2hs to go through more than 10 iterations, testing even visual feedback by discovering when testing that the player should quickly know when some action is disabled because of money restriction or not having unit slots available, etc. I even have to consider changing the scale of the game world to give more empty space reserved for the UI.

Player actions through delayed network

When playing network games, one thing that was a possible issue in my mind is that the player should receive feedback instantly even though the real action could be delayed a bit to be processed in the server. In the case of a move unit action in a RTS, the feedback could be just an animation showing the move destination and process the action later, but when the action considers a consuming a resource, that could be a little tricky, or at least I wasn’t sure so I decided to make a quick test for that.

Similar to the other, I created a Unity scene, in a separated project, I wanted to iterate really fast on this one. The idea to test was to have a way of processing part of the action in the client side to validate the preconditions (enough money) and to give the player instant feedback, and then process the action when it should.

After analyzing it a bit, my main concern was the player experience on executing an action and receiving instant feedback but watching the action was processed later, so I didn’t need any networking related code, I could test everything locally.

The test consisted in building white boxes with the right mouse button, each box costs $20 and you start with $100. So, the idea is that in the moment the button is pressed, a white box with half opacity appears giving the idea the action was processed and $20 are consumed, so you can’t do another action that needs more than that money. After a while, the white box is built and the preview disappear.

Here is a video showing it in action:

In the case of a server validating the action, it will work similar, the only difference is that the server could fail to validate the action (for example, the other player stole money before), in that case the player has to cancel it. So the next test was to try to process that case (visually) to see how it looks like and how it feels. The idea was similar to the previous case but after a while the game returns the money and the box preview disappears.

Here is a video showing this case in action:

It shouldn’t be a common case but this is one idea on how it could be solved and I don’t think it is a bad solution.

Different views of the same game world

The problem I want to solve here is how each player will see the world. Since I can’t have different worlds for each player the idea is to have different views of the same world. In the case of 3d games, having different cameras should do the trick (I suppose) but I wasn’t  sure if that worked the same way for a 2d game, so I have to be sure by making a prototype.

One thing to consider is that, in the case of the UI, each player should see their own actions in the same position.

For this prototype, I used the same scene background used for the mockups, but in this case I created two cameras, one was rotated 180 degrees to show the opposite:

(player 1 view)

(player 2 view)

Since UI should be unique for each player I configured each canvas for each camera and used the culling mask to show one or another canvas.

Again, this test was really simple and quick, I believe I spent like 30 mins on it, the important thing is that I know this is a possible (and probably the) solution for this problem, which before the test I wasn’t sure if it was a hard problem or not.

Conclusions

One good thing about making prototypes is that you could do a lot of shortcuts or assume stuff since the code and assets are not going to be in the game, that gives you a real fast iteration time as well as focus on one problem at a time. For example, by testing the mockups I added all assets in one folder and used Unity sprite packer without spending time on which texture format should I use for each mobile platform or if all assets can be in one texture or not, or stuff like that.

Making quick prototypes of things that you don’t know how to solve, early, gives you a better vision of the scope of problems and it is better to know that as soon as possible. Sometimes you could have a lead on how to solve them and how expensive the solution could be and that gives you a good idea on when you have to attack that problem or if you want it or not (for example, forget about a specific feature). If you can’t figure it out possible solutions even after making prototypes, then that feature is even harder than you thought.

Prototyping is cheap and it is fun because it provides a creative platform where the focus is on solving one problem without a lot of restrictions, that allows developing multiple solutions, and since it is a creative process, everyone in game development (game designers, programmers, artists, etc) could participate.


When building a platform for a game I tend to spend too much time thinking solutions for every possible problem, in part because it is fun and also a good exercise and in part because I am not sure which of those problems could affect the game. The idea of this post is to share why sometimes I believe it is better to delegate problems and solutions to the game instead of solving them in the engine.

In the case of the game state, I was trying to create an API on the platform side to be used by the game to easily represent it. I started by having a way to collaborate with the game state by storing values in it, like this:

public interface GameState {
  void storeInt(string name, int number);
  void storeFloat(string name, float number);
}

In order to use it, a class on the game side has to implement an interface which allows it to collaborate in part of the game state data:

public class MyCustomObject : GameStateCollaborator
{
  public void Collaborate(GameState gameState){
    gameState.storeFloat("myHealth", 100.0f);
    gameState.storeInt("mySpeed", 5);
  }
}

It wasn’t bad with the first tests but when I tried to use in a more complex situation the experience was a bit cumbersome since I had more data to store. I even felt like I was trying to recreate a serialization system and that wasn’t the idea of this API.

Since I have no idea what the game wants to save or even how it wants to save it, I changed a bit the paradigm. The GameState is now more like a concept without implementation, that part is going to be decided on the game side.

public interface GameState {

}

So after that change, the game has to implement the GameState and each game state collaborator will have to depend on that custom implementation, like this:

public class MyCustomGameState : GameState  
{
  public int superImportantValueForTheGame;
  public float anotherImportantValueForTheGame;
}

public class MyCustomObject : GameStateCollaborator
{
  public void Collaborate(GameState gameState)
  {
    var myCustomGameState = gameState as MyCustomGameState;
    myCustomGameState.anotherImportantValueForTheGame = 100.0f;
    myCustomGameState.superImportantValueForTheGame = 5;
  }
}

In this way, I don’t know or care how the game wants to store its game state, what I know is there is a concept of GameState that is responsible of providing the information the platform needs to make features, like a replay or savegame, work. For example, at some point I could have something like:

public interface GameStateSave 
{
    void Save(GameState gameState);
}

And let the game decide how to save its own game state even though the engine is responsible of how and when that interface is used to perform some task.

In the end, the platform/engine ends up being more like a framework, providing tools or life cycles to the user (the game) to easily do some work in a common way.