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
110k 55 185 669

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 guess we all call Javascript Unity Script here to be clear that it isn't actually Javascript. Unity internally compiles to a UnityScript dll when you write 'Javascript'

Jul 05, 2012 at 06:27 PM whydoidoit

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
(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 31 43

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:

x540
x38
x5

asked: Jul 05, 2012 at 04:00 PM

Seen: 6220 times

Last Updated: May 10 at 01:29 PM