- Home /
us of the "as" keyword (Instantiate, GetComponent)
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
var player1 : GameObject = Instantiate(playerDeathObj, dpos, playerDeathObj.transform.rotation) as GameObject ;
The other exemple is more important as it seems that the "AS" Solved the issue I was encountering :
var script1 : shipController = player1.transform.gameObject.GetComponent("shipController") as shipController ;
Answer by Drakestar · May 13, 2012 at 04:26 PM
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.
Answer by Eric5h5 · May 13, 2012 at 04:31 PM
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.
var player1 : GameObject = Instantiate(playerDeathObj, dpos, playerDeathObj.transform.rotation);
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
var script1 : shipController = player1.transform.gameObject.GetComponent(shipController);
(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.
@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.