x


How to perform Explicit typecasting in UnityScript?

Typecasting as in from Object to GameObject, int to float etc.

more ▼

asked Jul 05, 2012 at 04:00 PM

arkochelsea gravatar image

arkochelsea
20 6 4 8

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

You can use "as" for reference types.

 var foo : Object;
 var bar = foo as GameObject;

There isn't a direct method for value types, but you can use parseFloat or parseInt in the case of floats and ints.

more ▼

answered Jul 05, 2012 at 05:37 PM

Eric5h5 gravatar image

Eric5h5
112k 56 203 695

To be fair, he said "UnityScript" not Javascript, nor C#, nor Boo. So it wasn't very specific.

Jul 05, 2012 at 06:20 PM ThePunisher

I understand that, yet it is referenced as Javascript, not UnityScript. Nowhere in the documentation does it reference UnityScript.

Jul 05, 2012 at 06:36 PM ThePunisher

Actually, you can also convert value types through variables and it should be faster:

 var dNum: double = 3.5;
 var iNum: int = dNum;
 print("dNum=" + dNum + ", iNum=" + iNum);
 

As you can see, you don't need an explicit cast for value types. They are downcasted without a beep. Object to value type conversions don't work that way, though. There you'd need to use the aforementioned parse*() functions.

Jul 05, 2013 at 10:14 AM Simon Says

Of course you can always create extra variables, but it adds more lines of code and is less convenient than doing inline casting.

Jul 05, 2013 at 02:21 PM Eric5h5

Hi, what about typecasting a HashTable ValueType ?

 var stopwatchHashtable : Hashtable = new Hashtable();

 // in function
 var startTime : float = stopwatchHashtable[ theValue ];

gives me the expected warning BCW0028: WARNING: Implicit downcast from 'Object' to 'float'. But if I try to use :

 var startTime : float = parseFloat( stopwatchHashtable[ theValue ] ); 

I get an error BCE0004: Ambiguous reference 'parseFloat':

using as float; gives the error can only be used on objects

Edit :

Interestingly enough, this works ?!

 var startTime : float = parseFloat( stopwatchHashtable[ theValue ].ToString() );
May 09 at 02:03 PM alucardj
(comments are locked)
10|3000 characters needed characters left
 float myHealth = 10f;
 int healthA = myHealth as int;
 int healthB = (int)myHealth;
more ▼

answered Jul 05, 2012 at 05:36 PM

nventimiglia gravatar image

nventimiglia
500 38 32 46

Bizarrely, the question specifically asks for UnityScript and people post C# answers...not helpful....

Jul 05, 2012 at 05:37 PM Eric5h5
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x561
x38
x5

asked: Jul 05, 2012 at 04:00 PM

Seen: 6537 times

Last Updated: May 10 at 01:29 PM