Friday, 5 July 2013

Fun Fact: Unboxing in UnityScript

Let's write a code snippet in UnityScript that stores integers and strings in an associative array:

var container = new Hashtable();

container.Add("property1", 5);

container.Add("property2", "text");

var num: int = container["property1"];
print("num=" + num);


Retrieving the int value from the container emits a warning: “BCW0028: WARNING: Implicit downcast from 'Object' to 'int'.” But, since we want to maintain a clean code, how do we downcast explicitly?

This widely spread construct – var num: int = (int) container["property1"] – doesn't work. The operator as doesn't help neither; it only works for reference types. What do we do?

We turn to parsing text. Yes, seriously, the advice you'll get from every corner of the Unity community[1] and the only one that seems to work flawlessly so far is to use parseInt(). That means the value is printed to a string, then parsed back basically to the same value, but assigned a different type. All of this is going on in this short line of code:

var num: int = parseInt(container["property1"].ToString());

It's great we don't have to send it to a Unity server and wait until they parse it for us. Thank you, guys.

At the end of the day, it's a tough decision: Do we live with a log polluted with warnings, or do we parse text back and forth? Do you know of a better option?



By the way, C# has no issues with unboxing. This snippet works as expected:

var container = new Hashtable();

container.Add("property1", 5);
container.Add("property2", "text");

int num = (int) container["property1"];
Debug.Log("num=" + num);


No comments:

Post a Comment