|
Following tutorials I notice the use of the "as" keyword. I didn't find it in the programing reference. Its usage seems rather self explanatory but would like to get more information for my own understanding; I don't like to write blindly without understanding nor being unable to find the reference The other exemple is more important as it seems that the "AS" Solved the issue I was encountering :
(comments are locked)
|
|
Generally, the 'as' keyword performs a type conversion (a "cast") that evaluates to null if the conversion fails (as opposed to throwing an exception). That way, you can do a "if (x != null) check in the next line and react depending on whether the cast succeeded or not. BTW, that answer is C# specific. In Javascript, the as might not actually be necessary and only be there for good form. I don't use Javascript regularly.
May 13 '12 at 04:31 PM
Drakestar
(comments are locked)
|
|
The "as" keyword is used to cast the result to a specific type. However, in neither of those cases is it actually needed. Instantiate (in Unityscript) already returns the type of the prefab anyway, so it's completely unnecessary in the first example. Just remove it, since it's not doing anything. In the second example, GetComponent should not use strings (in almost all cases). With strings, GetComponent returns Object, so it needs to be cast, but without strings, GetComponent returns the type of the component. So it should read (Although "player1.transform.gameObject" is superfluous. Just do "player1.GetComponent(shipController)".) In the first example, the 'as' might help with UnityScript's static typing. Not necessary, but beneficial for runtime performance. This is just a guess without knowing any of the implementation details of the UnityScript compiler.
May 13 '12 at 04:35 PM
Drakestar
@Drakestar: no, it won't help at all. As I mentioned, Instantiate in Unityscript already returns the type of the prefab being instantiated anyway. Using "as" in this case won't hurt, but it won't help either, so you might as well not bother with it; it's completely redundant.
May 13 '12 at 04:44 PM
Eric5h5
(comments are locked)
|
