• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
  • entries
    11
  • comments
    16
  • views
    17104

About this blog

Thoughts on development, game engines, code, tools, etc

Entries in this blog

Liort
Hey All !

The slides from our presentation on "Unity and WebGL" are now available here: http://bit.ly/1G8Ju5f

We talked about the process of getting our game "Wonderball Heroes" to WebGL, and all the challenges, optimizations and other bugs we faced along the way.

It's pretty technical, but may be really helpful for all of you planning to support this platform with Unity 5.

Check it out, and feel free to comment / contact me in case you have any questions !
Liort

Auto Save for Unity

This article was originally posted on Random Bits. Check it out for more Unity related content.
What can you do when a team member suffers a recurring Unity editor crash, losing all level design work ? My answer was to write a small and helpful editor extension - auto save! (and then blog about it).

TL;DR



This post describes a simple solution for implementing auto save in Unity that saves the currently open scene every 5 minutes (configurable).
The code is available for easy consumption in a few ways:

  • GitHub - Also updated in case i get any feedback / future posts
  • Gist

    The code is imported and works out of the box, import / paste it into your Unity project and you're good to go.

    Problem



    It started a few days ago: a member of our team started experiencing occasional Unity editor crashes a few times daily. We do not know the exact reason for crashes, but we suspect it may be related to memory issues combined with voodoo magic. No matter what the root cause was, these crashes caused real damage in lost data (game levels) which we could not afford having.
    In order to keep lost work to a minimum, I suggested to implement a basic auto save solution, so at least we can go back to a backup in case the editor crashes.

    Solution - AutoSave



    The solution uses pretty simple editor scripting to the rescue. The process can be described in 3 main steps:


    1. Hook a delegate to EditorApplication.update.
    2. In this method, check if the scene should be saved (if the configured time has elapsed. The default is 5 minutes).
    3. In case we need to save, generate a new unique name for the scene and save it to disk.

    In order to have the code up and running when you launch the editor, the class is marked with the [InitializeOnLoad] attribute and initialization is done in its static constructor.

    Show Me the Code



    This is the complete code, you can paste it into your project:using System;using System.IO;using System.Globalization;using UnityEditor;using UnityEngine; [InitializeOnLoad]public class AutoSaveScene{ private const string SAVE_FOLDER = "Editor/AutoSaves"; private static System.DateTime lastSaveTime = System.DateTime.Now; private static System.TimeSpan updateInterval; static AutoSaveScene() { EnsureAutoSavePathExists(); // Register for autosaves. // Change this number to modify the autosave interval. RegisterOnEditorUpdate(5); } public static void RegisterOnEditorUpdate(int interval) { Debug.Log ("Enabling AutoSave"); updateInterval = new TimeSpan(0, interval, 0); EditorApplication.update += OnUpdate; } /// /// Makes sure the target save path exists. /// private static void EnsureAutoSavePathExists() { var path = Path.Combine(Application.dataPath, SAVE_FOLDER); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } } /// /// Saves a copy of the currently open scene. /// private static void SaveScene() { Debug.Log("Auto saving scene: " + EditorApplication.currentScene); EnsureAutoSavePathExists(); // Get the new saved scene name. var newName = GetNewSceneName(EditorApplication.currentScene); var folder = Path.Combine("Assets", SAVE_FOLDER); EditorApplication.SaveScene(Path.Combine(folder, newName), true); EditorApplication.SaveAssets(); } /// /// Helper method that creates a new scene name. /// private static string GetNewSceneName(string originalSceneName) { var scene = Path.GetFileNameWithoutExtension(originalSceneName); return string.Format( "{0}_{1}.unity", scene, System.DateTime.Now.ToString( "yyyy-MM-dd_HH-mm-ss", CultureInfo.InvariantCulture)); } private static void OnUpdate() { if ((System.DateTime.Now - lastSaveTime) >= updateInterval) { SaveScene(); lastSaveTime = System.DateTime.Now; } }}

    Built In AutoSave



    It should be noted that apparently Unity does autosave the current scene every time you enter play mode. If this is enough for you (for example - the game crashed during play mode), a copy of the scene can be found in YourProject/Temp/__EditModeScene.

    Conclusion



    The code in this post helps ensuring no scene data is lost when experiencing editor crashes. I deliberately kept it short & simple so it can be easily "digested". Autosaving can be further visited by adding any of the following:

    • Configuration - Allow controlling autosave (turning on/off, setting time interval) from an editor window or menu item.
    • Capping number of autosaves - Nobody really needs 50 copies of the open scene; instead, only 1 or 2 copies can be saved and recycled on every new save.
    • New save triggers - The current code saves every X minutes. The code can be adapted to save under different scenarios.

      Related Resources

Liort
For those who are working with Unity and ScriptableObjects, one concern is how to actually instantiate scriptable objects.
The editor does not have any out-of-the-box option for doing so, and you have to do that manually in code for every type of object you define.

I have posted a new entry on my blog, containing a generic solution for this issue - an editor extension that will allow you to easily create ScriptableObject instances of any kind directly from the editor.

Please check out the post here - http://www.tallior.com/2014/08/06/unity-scriptableobject-factory/

Let me know if you find it helpful !
Liort
As of yesterday, after being laid off (with pretty much everybody else) form the company I worked in, I am officially unemployed.

I would like to request your assistance for feedback on my newly updated CV - what is missing? what should be added, removed or rearranged?

Any help will be appreciated !

Here's the link: http://goo.gl/htIklF
Liort
[color=#757575]This post was originally posted on my blog at [/color]http://www.tallior.com
Many Unity code samples use a string identifier, such as the game object's tag for various things (e.g: checking for a collision with "player"). In this post i will explore a different, safer and automated technique that achieves the same result, but does not require using strings.

The String Problem


Consider the following code:

string_lookup.png

The code is not type safe: it relies on a string identifier to perform an object lookup. This identifier may change, making this code "out of sync" with the project, or be misspelled, making the code fail. In addition, this string might be used in many different locations of the code, increasing the risk of previous mentioned concerns.

A Solution "Sketch"


A possible solution to this issue is to create a static helper class that will expose all tags as public (static) fields. When needed, Instead of using a string, we'd use the class's static fields:

static_class.png


Accessing this tag is safer now, since we're not (directly) relying on the string representation of the tag:

safe_access.png


Effectively, the code will operate the same as before, but now we have a single location where the tag is declared.
There are 2 main issues with this approach:

  1. In case there are many tags defined in the project, creating the helper class can be a somewhat tedious task (creating a field per tag).
  2. In case a tag's name changes in the Unity editor, you have to also remember to replace it's corresponding value in the helper class.

It seems that this solution is a step in the right direction, but we need some extra "magic" to make it perfect.

Code Generation To The Rescue


Code generation is an (sometimes) overlooked practice, where code is being automatically generated by some other code, a template or some tool.

In particular, code generation really shines in cases where we want to generate long, repetitive code from an underlying data source.
Translating this to the problem described above, we would like to generate a static helper class with many static fields from an underlying data source (a collection with all of the project's tags).

46974122-300x271.jpg


To achieve this, we'll use one particular implementation of a code generation engine called T4:
T4 is a template engine that comes with Visual Studio (which also heavily relies on it for various tasks), and also comes out of the box with Mono (yes, the same one that is installed with Unity).
A T4 template is a file (with a .tt extension) that mixes a body of text with special directives. The template generates a single output file (usually, a code file, although it can generate any other file format).

T4 Templates


In order to add a T4 template to your project, right click on your code project in MonoDevelop, and select: Add->New File. T4 Templates can be found under Text Templating on the left:

t41.png

T4 Template Types



There are 2 types of available templates (ignore Razor templates as they're irrelevant for this discussion):

  1. T4 Template - a template file that gets transformed during compilation time into the output file. This type of template is used to generate code files that are needed at design time (e.g: think of Microsoft's Entity Framework, where a set of classes can be generated at design time from a database, instead of being created manually by the developer).
  2. Preprocessed T4 Template - a template file that creates an "intermediate" class that can later be used to generate the output code file.

Unity currently does not support adding T4 templates (.tt files) to scripting code - after compilation, all .tt files will be dropped from the code project (I reported this bug here: T4 Bug)

This forces us to use option #2 - creating a one-time "intermediate" class. This class will be used by a Unity edior extension, from which we can generate the class we want and add it to the project.

Show Me the Code!



Here is the preprocessed T4 template that will generate the Tags class for us (although the provided sample uses the same template to generate a Layers class in exactly the same manner):

t4_example.png

A few things that should be noted:

  1. Any text that not contained within <# #> tags is being output as is.
  2. The template is a preprocessed template. This means it does not generate an output code file directly. Instead, it generates an intermediate (partial) class with a TransformText() method that returns the template final output (the text with the generated class).
  3. The code prints out a header (the class declaration with some comments), then it iterates all elements in source and outputs a public static readonly field for each item (does a small manipulation to make sure the field name does not have spaces in it).
  4. The variables classname, item and source are actually implemented in a code file (a partial class with the same name as the template class. Remember I said the template generates a partial class? this allows mixing the template with some custom code. For more clarity, see the full code in the link below).

In Conclusion



This post aimed to open a hatch to the wonderful world of code generation (and T4 in specific), while showing how it can solve real world problems in a short and simple way.
I did not dive into T4 syntax or more advanced topics (leaving it for you to explore, or as a subject for future posts). For more information regarding T4 - see the links below.

Links

Liort
This post originally appeared on my blog on http://www.tallior.com/2014/02/08/bug-hunting-unity-throws-an-argumentexception-when-building-for-android/

[color=#333333][font=Georgia]

What can be done when Unity mysteriously throws an ArgumentException when building a project for Android? In this post I'll describe the techniques and tools I used to track down the root cause for this issue.

[/font][/color]

Prologue



[color=#333333][font=Georgia]

When using a tool such as Unity, a simple click of a "Build" button often hides a long and complex process involving different modules and tools. When this process fails, it may be hard to determine the exact reason. One approach would be to try looking for what you did wrong (what did I install? did I pass the wrong parameters somewhere?).

[/font][/color]

[color=#333333][font=Georgia]

A different approach - the one we'll explore today, is to dig deeper under the surface to look for the cause of error.

[/font][/color]

Reproduction



[color=#333333][font=Georgia]

The first stop when attempting to fix an issue is to reproduce it at will. Since the original issue was reported by another user, I started by attempting to get the same exception on my machine: I launched Unity, and tried to build an empty project for Android.

[/font][/color]
[color=#333333][font=Georgia]

Lucky for me, the stars aligned, and I got the exception on the first attempt, without doing anything special. Many times, reproducing another user's problem won't be that easy, and in that case these steps should be performed directly on the machine that demonstrated the error.

[/font][/color]

How did I get here? (Getting context)


[color=#333333][font=Georgia]

As a developer, you are in control of what errors are shown to your users. This means that internal errors and exceptions may be caught internally ("swallowed") and silenced or replaced by some other, more friendly message.

[/font][/color]
[color=#333333][font=Georgia]

In our case, the only piece of information at hand is this message displayed in the Unity console:

[/font][/color]
[color=#333333][font=Georgia]

Error_thumb1.png

[/font][/color]
[color=#333333][font=Georgia]

Unfortunately, this doesn't reveal any information as to where this happened, nor what Unity attempted to do at that time.

[/font][/color]
[color=#333333][font=Georgia]

Getting a proper context is important for understanding what went wrong.

[/font][/color]
[color=#333333][font=Georgia]

Since this exception looks like it comes from internal Unity code written in C# (Mono), we can use the debugger and break execution when this specific exception occurs.

[/font][/color]

Breaking on a specific exception


[color=#333333][font=Georgia]

This is a very useful debugger feature that allows breaking execution when particular exception types are thrown (similar to setting a breakpoint).

[/font][/color]
[color=#333333][font=Georgia]

We need to configure the debugger to break on ArgumentException. This is done by launching MonoDevelop and running these steps:

[/font][/color]

  1. Attach to the running Unity process (Run -> Attach to Process)
  2. Open the Exceptions menu (Run -> Exceptions)
  3. Add System.ArgumentException to Stop in exceptions:

[color=#333333][font=Georgia]

ExceptionsMenu_thumb.png

[/font][/color]
[color=#333333][font=Georgia]

After hitting OK, the debugger is properly configured, and indeed when repeating the build in Unity, the debugger breaks exactly as the ArgumentException is thrown, and we can examine the stack trace:

[/font][/color]
[color=#333333][font=Georgia]

StackTrace_thumb5.png

[/font][/color]
[color=#333333][font=Georgia]

At this point, we have the first piece of information we need - the exception is thrown after calling Path.Combine with some weird first argument (see path1).

[/font][/color]

Going in reverse


[color=#333333][font=Georgia]

With the stack trace in hand, we must dig a bit deeper to understand how unity got that weird looking path that was used for the call to Path.Combine.

[/font][/color]

Decompiling


[color=#333333][font=Georgia]

Using a C# decompiler (Reflector, dotPeek), we can peek at the code in the UnityEditor.Android.dll assembly (located under the Unity installation folder).

[/font][/color]
[color=#333333][font=Georgia]

Looking at the method at the top of the stack trace, we can see the call to Path.Combine:

[/font][/color]
[color=#333333][font=Georgia]

reflector_path_combine_thumb1.png

[/font][/color]
[color=#333333][font=Georgia]

Since the first argument to Path.Combine is the interesting one, we'd like to know how does SDKBuildToolsDir receive its value. This is pretty easy using the decompiler, and we can see that this is how it gets its value:

[/font][/color]
[color=#333333][font=Georgia]

reflector_sdkbuildtoolsdir_thumb1.png

[/font][/color]
[color=#333333][font=Georgia]

It appears that Unity is running some external command whose output is captured and is assigned to SDKBulidToolsDir. We can now attempt to see how the code assembles the command line and invokes the tool, but there's a better and easier option.

[/font][/color]

Sniffing for processes


[color=#333333][font=Georgia]

Process Monitor (procmon) is a nifty little tool that acts as a "sniffer" for various real-time machine wide activities (process information, networking, registry access, file access). It is particularly useful for figuring out what processes were invoked (by Unity), and what were their arguments.

[/font][/color]
[color=#333333][font=Georgia]

Running procmon and then starting a new build gives us a nice capture of the data we need. After the build fails we can stop procmon from capturing (CTRL-E) to keep the captured trace clean and focused on the issue at hand. The trace will probably contain information from many running processes, but we can filter it to show events originating from Unity.exe. This is done by right-clicking a trace line from Unity.exe and selecting "Include Unity.exe"):

[/font][/color]
[color=#333333][font=Georgia]

procmon_filter_thumb.png

[/font][/color]
[color=#333333][font=Georgia]

We should further filter the results for showing only process/thread activities (from the toolbar), as seen in this image:

[/font][/color]
[color=#333333][font=Georgia]

procmon_process_thumb.png

[/font][/color]
[color=#333333][font=Georgia]

This gets us only Unity.exe traces of process and thread events. From this point it's pretty straightforward to find that Unity creates a new Java process with the following details (paths may vary on your machine):

[/font][/color]
[size=2][color=#333333][font=Georgia][background=transparent][background=transparent]"C:\Program Files\Java\jdk1.7.0_17\bin\java.exe"[/background] -Xmx1024M -Dcom.android.sdkmanager.toolsdir=[background=transparent]"D:/Android/sdk\tools"[/background] -Dfile.encoding=UTF8 -jar [background=transparent]"D:/Unity/Editor/Data/BuildTargetTools/AndroidPlayer\sdktools.jar"[/background] -[/background][/font][/color]
[color=#333333][font=Georgia]

Running this exact command from a command prompt generates this output:

[/font][/color]
[color=#333333][font=Georgia]

picked_up_thumb.png

[/font][/color]

Eureka!


[color=#333333][font=Georgia]

Putting it all together, from all we've learned it looks like Unity is using a custom Java based tool, captures its output in a variable and uses that information as part of the build process. In cases where _JAVA_OPTIONS environment variable is defined, Java will print out the options used to the console (this will happen also when invoking java with no arguments), however Unity's build process does not deal with this scenario very well.

[/font][/color]
[color=#333333][font=Georgia]

The issue was reported and acknowledged by Unity in this Bug Report

[/font][/color] Takeaways

  1. Reproduce the issue before attempting to fix it
  2. Determine a context for the failure (e.g: stack trace)
  3. Reverse engineering can be your friend

Tools Used
Sign in to follow this  
Followers 0