Unity Helper – Enumerate Resources

Unity Helper – Enumerate Resources

Following on from yesterdays post on my Unity-Helpers I have added another utility to the library.

Enumerate Resources

Enumerate Resources is a handy util for creating type-safe resource references. Traditionally you have to manually create constant strings to load resources at runtime:

Resources.Load("Prefabs/Cars/Porsche");

This is fragile. If the asset is moved you wont know about the crash until you run the game, this line of code may not be executed often and hence introduces a bug that may only present itself at a later date.

Enumerate Resources scans a resources directory and generates a type-safe alternative:

Resources.Load(GameResources.Prefabs.Cars.Porsche);

Now if you move the resource and run the enumerator you will get a compile error.

For added sugar there is a method to add the loaded resource as a child of a game object (handy for prefabs):

obj.LoadChild(GameResources.Prefabs.Icons.IndicatorArror);

You can grab the project, source and tests over at Github: https://github.com/mikecann/Unity-Helpers

Unity Helpers – Utilities and Extensions for Unity

Unity Helpers – Utilities and Extensions for Unity

During the development of my up and coming game I have encountered some snags when developing in Unity so I wrote a number of utilities and extension methods to help out.

One such annoyance is the inability to use interfaces in GetComponent() and GetComponents(), so I wrote some extension methods to help with that:

using UnityHelpers;

var obj = new GameObject();
obj.AddComponent<MyComponent>();

obj.Has<MyComponent>(); // Returns true or false
obj.Has<IMyComponent>(); // Can also handle interfaces

obj.Get<MyComponent>(); // Returns the first component
obj.Get<IMyComponent>(); // Returns the first component that implements the interface

obj.GetAll<MyComponent>(); // Gets all the components
obj.GetAll<IMyComponent>(); // Gets all the components that implement the interface

Another utility is for adding children to GameObjects:

using UnityHelpers;

var obj = new GameObject();

obj.AddChild("Mike"); // Creates a new GameObject named "Mike" and adds it as a child

var player = obj.AddChild<Player>("Dave"); // Creates a new GameObject named "Dave" and adds the component "Player" returning it

obj.AddChild(typeof(Player), typeof(Friendly), typeof(AI)); // Creates a new GameObject and adds a number of components

There are many other utils and extensions, and more to come.

Checkout the source for more info: https://github.com/mikecann/Unity-Helpers/tree/master/Scripts

I have rigorously unit and battle tested these utils and added them to Github so I can use them in furthur projects. I hope they can be of some use to others too!

Fixing Unity’s Internal Compiler Error

Fixing Unity’s Internal Compiler Error

As mentioned in my last post, I am working on a Unity game that takes advantage of Parse for Asyncronous multiplayer. Well one nice feature of parse is that it uses Tasks to handle its asynchronicity.

Tasks are very much like JS promises (except they are type-safe) and return when the operation has completed. For example:

obj.SaveAsync().ContinueWith(task =>
{
    if (task.IsCanceled)
    {
        // the save was cancelled.
    }
    else if (task.IsFaulted)
    {
        AggregateException exception = task.Exception;
    }
    else
    {
        // the object was saved successfully.
    }
});

You can chain tasks together like so:

var query = new ParseQuery<ParseObject>("Student")
    .OrderByDescending("gpa");
 
query.FindAsync().ContinueWith(t =>
{
    var students = t.Result;
    IEnumerator<ParseObject> enumerator = students.GetEnumerator();
    enumerator.MoveNext();
    var student = enumerator.Current;
    student["valedictorian"] = true;
    return student.SaveAsync();
}).Unwrap().ContinueWith(t =>
{
    return query.FindAsync();
}).Unwrap().ContinueWith(t =>
{
    var students = t.Result;
    IEnumerator<ParseObject> enumerator = students.GetEnumerator();
    enumerator.MoveNext();
    enumerator.MoveNext();
    var student = enumerator.Current;
    student["salutatorian"] = true;
    return student.SaveAsync();
}).Unwrap().ContinueWith(t =>
{
    // Everything is done!
});

The problem is that if you want to catch errors you must manually check the task return for errors inside each handler. This seemed wasteful to me as all I wanted was a global error handler for that particular task chain, such as can be achieved with Javascript Promises.

Fortunately someone else also had noticed this problem and solved it:

Task.Factory.StartNew(StartBusyIndicator)
	.Then(task => GetWebResponseAsync(url))
	.Then(task => Console.WriteLine(task.Result.Headers))
	.Finally(ExceptionHandler, StopBusyIndicator);

The only problem is that when I tried to implement his C# library Unity started throwing the dreaded Internal Compiler Error:

Internal compiler error. See the console log for more information. output was:
Unhandled Exception: System.ArgumentNullException: Argument cannot be null.

It took me a while to work out what was going on. I managed to simplify the entire problem down to this simple example:

public static class TaskHelpers
{
	public static void Then<TIn>(this Task<TIn> task, Action<Task<TIn>> next)
	{
		task.ContinueWith(t =>
		{		
		});    
	}
}

I posted about this on the Unity forum on Parse’s Forum and even on Parse’s bug tracking system but no one was interested, Parse even told me its not a Parse issue.

It took me quite a while to work out what was going on, but I eventually worked out that if I separated the handler from the Continue With call it would work:

public static class TaskHelpers
{
	public static void Continue<TIn>(this Task<TIn> task, Action<Task<TIn>> next)
	{
		Action<Task> a = t => { };
		task.ContinueWith(a);    
	}
}

Huzzah! It compiles. So I guess this is a lesson learnt. With the Unity Mono compiler, if you are getting Internal Compiler errors then perhaps try separating out the lambdas into variables.