Game Development Reference
In-Depth Information
Casting
JavaScript automatically casts from one type to another, where possible. For example, the
Instantiate command returns a type of Object , as shown in the following code:
// JavaScript user:
//There's no need to cast the result of "Instantiate"
provided the variable's type is declared.
var newObject : GameObject = Instantiate(sourceObject);
// C# user:
// in C#, both the variable and the result of instantiate
must be declared.
// C# first version
GameObject foo = (GameObject) Instantiate(sourceObject);
// C# second version
GameObject foo = Instantiate(sourceObject) as GameObject;
Tip
There are two different ways of casting in C#. For the first line in the preceding code, if the
object can't be instantiated, it will throw an exception. You will need to use a try/catch
statement to handle this exception properly. The second line, if it fails, will set foo to
null and not throw an exception. Then, you would just need to test if the returned object
is null or not.
Search WWH ::




Custom Search